Home > OS >  Does gcp firestore in datastore mode support OR query?
Does gcp firestore in datastore mode support OR query?

Time:12-30

Consider following data in GCP datastore:

users: [
{name: 'jane', email: '[email protected]', user_id: 1},
{name: 'jacob', email: '[email protected]', user_id: 2},
{name: 'john', email: '[email protected]', user_id: 3}
]

relations: [
{user1_id: 1, user2_id: 2, relation_name: "spouse"},
{user1_id: 2, user2_id: 3, relation_name: "father_son"}
]

I want to fetch all relations for user jacob for that I need to query for jacob's ID in two columns that is user1_id & user2_id using some sort of OR logic while running datastore query but I am unable to find any document with the required example to make OR query.

Is this possible in one query else I will have to make two separate query one with column user1_id and other user user2_id.

I am using firestore in datastore mode and I am using node js client library to fetch result.

CodePudding user response:

GCP Firestore in datastore mode does not natively support 'OR' operator but some client libraries add the support for 'OR' operator. Check Restriction on quarries for more details.

CodePudding user response:

Yes, it is possible to perform a query using the "OR" operator in Google Cloud Datastore.

To fetch all relations for the user with the name "jacob", you can use a query with a filter that specifies that either the "user1_id" or the "user2_id" should be equal to the "user_id" of the user with the name "jacob".

Here is an example:

# First, retrieve the "user_id" of the user with the name "jacob"
query = client.query(kind='users')
query.add_filter('name', '=', 'jacob')
results = list(query.fetch())
jacob_id = results[0]['user_id']

# Now, fetch all relations where either the "user1_id" or the "user2_id" is equal to the "user_id" of the user with the name "jacob"
query = client.query(kind='relations')
query.add_filter('user1_id', '=', jacob_id)
query.add_filter('user2_id', '=', jacob_id)
query.add_operator('OR')
results = list(query.fetch())

This will return all entities of kind "relations" where either the "user1_id" or the "user2_id" is equal to the "user_id" of the user with the name "jacob".

  • Related