(solved)SELECT : return Document ID / KEY of documents in Golang

n1ql

#1

Hi there,
I am doing a select in Golang for json document that have the field Token = “My requested value”.
What I am looking for is the list of documents ID (KEY) that contain this specific token.
I am doing this request:
query := gocb.NewN1qlQuery(“SELECT meta(person).id FROM restful-sample AS person WHERE token = $1”)
params := mux.Vars(req)
n1qlParams = append(n1qlParams, params[“token”])
rows, _ := bucket.ExecuteN1qlQuery(query, n1qlParams)

var row2 interface{}
for rows.Next(&row2) {
json.NewEncoder(w).Encode(row2)
fmt.Printf(“Row: %+v\n”, row2)

}

Which works QUITE well :wink:
json.NewEncoder(w).Encode(row2) ; gives me a very nice JSON.

But I have a very hard time getting the actual ID of the document within my GO code :frowning:

fmt.Printf(“Row: %+v\n”, row2); gives : map[id:dde708a8-6fb5-491c-ac5a-15ef4be89318]

json.NewEncoder(w).Encode(row2); gives {
“id”: “dde708a8-6fb5-491c-ac5a-15ef4be89318”
}

i m sure it must be something simple, but don t find the solution.
Thanks for your help
Ian


#2

Try using row2["id"]


#3

Hello @vsr1,

I get :

./main.go:158: invalid operation: row2[“id”] (type interface {} does not support indexing)

Thanks for your help vsr1

PS: I am also interested if there is a code snippet somewhere demonstrating this comon case; where you whant the document IDs of a SELECT


#4

@tgreenstein will be able to help here.


#5

Hey @Iann,

You should be able to map the results into an actual concrete structure rather than an arbitrary map (which is what interface{} will decode a JSON object into), try something like this:

var row struct {
  Id string `json:"id"`
}
for rows.Next(&row) {
  fmt.Printf("ID: %s\n", row.Id)
}

Cheers, Brett


#6

Dear @brett19,

Thanks a lot it wored!
I tried it this way actually first (like I did before in my code) but for some reason I did it wrong…
Id did it with the struct and it works perfectly now :smiley_cat:
var row N1qlID
rows.One(&row)
json.NewEncoder(w).Encode(row.Id)

Again thanks!

PS: if there is a simpler version to get the document ID for a SELECT i d still be interested :wink: