In App Engine datastore, performing an "IN" query with a slice of integers is not directly supported using the Filter function. However, several approaches can be employed to achieve similar functionality.
One option is to create a separate query for each element in the integer slice. This approach is suitable if the number of elements is relatively small.
<code class="go">ids := []int64{1, 2, 3, 4} var q datastore.Query for _, id := range ids { q = q.Filter("Id =", id) }</code>
If the elements in the integer slice represent a continuous range, you can use range operators (>= and <=) to substitute the IN filter.
<code class="go">ids := []int64{1, 2, 3, 4} q := datastore.NewQuery("Category"). Filter("Id >=", 1). Filter("Id <=", 4)</p> <h3>Approach 3: GetMulti for Key IN Query</h3> <p>If the property being filtered is the entity key, you can use the datastore.GetMulti() function to retrieve multiple entities based on an array of keys.</p> <pre class="brush:php;toolbar:false"><code class="go">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)</code>
Note:
The second approach using multiple Filter calls does not work correctly. Applying multiple filters in this manner results in a logical AND connection, and no entities will likely satisfy all the conditions simultaneously.
The above is the detailed content of How to Perform 'IN' Queries with Integer Slices in Google App Engine Datastore with Go?. For more information, please follow other related articles on the PHP Chinese website!