Cloud Firestore: text search

Viewed 37

I am trying to find users by Europe/Chisinau timezone. An example of such a user:

'device':{
    'from':'{"status":"success","country":"Moldova","countryCode":"MD","zip":"MD-3300","timezone":"Europe/Chisinau"}'
}

Here the from field is a string. Here's what I've tried using:

In [1]: from google.cloud import firestore
   ...: firestore_client = firestore.Client.from_service_account_json('creds.json')
   ...: ref = firestore_client.collection('databases').document('testing')
In [2]: ref.collection(u'users').where(u'device.from', u'>=', u'Europe/Chisinau').where(u'device.from', u'<=', u'Europe/Chisinau').get()
Out[2]: []

As you can see, I got an empty list. I have used this module.

1 Answers

It looks like your from field is a single string value, in which you've encoded a JSON object. You won't be able to query individual parts of the JSON object in such a case, as Firestore can only search from the start of the string. So this may work:

ref.collection(u'users').where(u'device.from', u'>=', u'{"status":"success"').where(u'device.from', u'<=', u'{"status":"updated"')

The above may work, because it's what the from field starts with. But you cannot search for values in other part of the string.


If you want to be able to search the individual parts of your JSON object, consider storing it as a map instead of a string:

'device':{
  'from': {
    "status": "success",
    "country":"Moldova",
    "countryCode":"MD",
    "zip":"MD-3300",
    "timezone":"Europe/Chisinau"
  }
}

Now you can perform the query with:

ref.collection(u'users').where(u'device.from.timezone', u'==', u'Europe/Chisinau')
Related