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

喜夏-厌秋 提交于 2019-11-28 13:43:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!