Google Datastore filter with OR condition

2019-06-21 08:36发布

I am working with NodeJS on Google App Engine with the Datastore database.

I am using composite query filter and just need a basic "OR" condition.

Example: Query Tasks that have Done = false OR priority = 4

const query = datastore.createQuery('Task')
  .filter('done', '=', false) //How to make this an OR condition?
  .filter('priority', '=', 4);

However, according to the documentation:

Cloud Datastore currently only natively supports combining filters with the AND operator.

What is a good way to achieve a basic OR condition without running two entirely separate queries and then combining the results?

UPDATE

I have my solution described in detail here in my other post. Any feedback for improvements to the solution would be appreciated since I'm still learning NodeJS.

1条回答
孤傲高冷的网名
2楼-- · 2019-06-21 09:01

Not currently possible to achieve a query with an OR condition - this is what the note you quoted means.

Some client libraries provide some (limited) support for OR-like operations. From Restrictions on queries:

The nature of the index query mechanism imposes certain restrictions on what a query can do. Cloud Datastore queries do not support substring matches, case-insensitive matches, or so-called full-text search. The NOT, OR, and != operators are not natively supported, but some client libraries may add support on top of Cloud Datastore.

But AFAIK no such library is available for NodeJS.

If you only have a need for a few specific such queries one possible approach would be to compute (at the time of writing the entities) an additional property with the desired result for such query and use equality queries on that property instead.

For example, assuming you'd like a query with OR-ing the equivalents of these filters:

  • .filter('status', '=', 'queued')
  • .filter('status', '=', 'running')

You could compute a property like not_done every time status changes and set it to true if status is either queued or running and false otherwise. Then you can use .filter('not_done', '=', true) which would have the same semantics. Granted, it's not convenient, but it may get you past the hurdle.

查看更多
登录 后发表回答