Steven Lu
Steven Lu

Reputation: 2180

Doing a "IN Array" query on google app engine datastore with golang

Is there a way to do a query with ids []int64 on datastore? I've tried the following with no avail.

  1. Errors out

    q := datastore.NewQuery("Category").Filter("Id IN", ids)
    
  2. Just gets me all the the categories in the datastore

    for _, id := range ids {
        q.Filter("Id =", id)
    }
    

After icza's answer

var keys []*datastore.Key

for _, id := range ids {
    keys = append(keys, datastore.NewKey(c, "Category", "", id, nil))
}

categories := make([]Category, len(keys))
err := datastore.GetMulti(c, keys, categories)
if err != nil {
    return nil, err
}

Upvotes: 5

Views: 4058

Answers (1)

icza
icza

Reputation: 417452

Generally "IN" filters are not supported by the Datastore. The documentation of Query.Filter() lists the allowed operators:

">", "<", ">=", "<=", or "="

What you can do is execute a separate query for each of the elements in the array you want to filter by. Also if the elements are in a continous range, you can substitute the IN with id>=min and id<=max. E.g.:

ids := []int64{1,2,3,4}
q := datastore.NewQuery("Category").Filter("Id>=", 1).Filter("Id<=", 4)

Also note that while the IN is not supported in general, if the property is the entity key itself, you can get a list of entities specified by an array of their keys using the datastore.GetMulti() function:

func GetMulti(c appengine.Context, key []*Key, dst interface{}) error

Note:

Your 2nd attempt returns all entities because you call Filter() on your query, but you don't store the return value, so the query you end up executing will have no filters at all. Query.Filter() returns a derivative query which contains the filter you just specified, you have to use the returned Query ongoing. So it should be:

q = q.Filter("Id=", id)

But even this won't work either: if multiple filters are specified, they will be in logical AND connection so it will most likely give you 0 results as I suspect no category will exists where Id is a list and which would contain all the ids you want to filter by.

Upvotes: 5

Related Questions