Is there a possibility to perform non-case sensitive "where" request to Firestore - firebase

I have a request to Firestore to check if the collection of tickets contains some duplicated IDs:
firestore.collection("tickets").where("extId", "==", "Test 2").get();
The problem is - where method looks up only for case-sensitive IDs.
Is there a chance I can return a document with test 2 or tesT 2 extId?

Unfortunately Firestore queries are case sensitive and there is no way to avoid this. Here are some approaches you could take to solve this problem depending on your use case:
1. Store several versions of your data (eg store both an upper and lower case version of your data)
2. Don't allow users to type in their query, and instead provide them with predefined filter items (for example chips, or a dropdown menu)
3. Do some client side processing before executing the query (eg. convert query strings into upper or lowercase to ensure it matches the format in the document)
4. Use a search engine platform on top of Firestore such as Algolia, Typesense, Meilisearch, among others as they contain typo-tolerance and other additional features

As also #Hydra mentioned in her answer, the queries in Firestore are case-sensitive, meaning that will always return documents with the exact match. If you want to get documents with test 2 OR tesT 2, then you should consider using in operator:
Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR. An in query returns documents where the given field matches any of the comparison values.
In your particular case, the following query will do the trick:
firestore.collection("tickets").where("extId", "in", ["test 2", "tesT 2"]).get();

Related

firebase query - find doc where map value is in an array

I'm trying to find the id of a doc where a map value in an array of maps equals "x".
in the following case, I'm trying to find which rep owns the cause with code "hog"
I'll likely be going down the denormalizing route, but is this possible?
Firestore has an array-contains operator that you can use to query whether a certain item exists in an array field, but that operator only works if you specify the exact, complete value of the field. It can't test for a partial match.
The common approach to your use-case is to add an additional array field with just the values you want to query on, i.e.
cause-codes: ["hog"]
Once you modified your documents with this additional field, you can then use a query like:
repsRef.where('cause-codes:', 'array-contains', 'hof')

How can I limit and sort on document ID in firestore?

I have a collection where the documents are uniquely identified by a date, and I want to get the n most recent documents. My first thought was to use the date as a document ID, and then my query would sort by ID in descending order. Something like .orderBy(FieldPath.documentId, descending: true).limit(n). This does not work, because it requires an index, which can't be created because __name__ only indexes are not supported.
My next attempt was to use .limitToLast(n) with the default sort, which is documented here.
By default, Cloud Firestore retrieves all documents that satisfy the query in ascending order by document ID
According to that snippet from the docs, .limitToLast(n) should work. However, because I didn't specify a sort, it says I can't limit the results. To fix this, I tried .orderBy(FieldPath.documentId).limitToLast(n), which should be equivalent. This, for some reason, gives me an error saying I need an index. I can't create it for the same reason I couldn't create the previous one, but I don't think I should need to because they must already have an index like that in order to implement the default ordering.
Should I just give up and copy the document ID into the document as a field, so I can sort that way? I know it should be easy from an algorithms perspective to do what I'm trying to do, but I haven't been able to figure out how to do it using the API. Am I missing something?
Edit: I didn't realize this was important, but I'm using the flutterfire firestore library.
A few points. It is ALWAYS a good practice to use random, well distributed documentId's in firestore for scale and efficiency. Related to that, there is effectively NO WAY to query by documentId - and in the few circumstances you can use it (especially for a range, which is possible but VERY tricky, as it requires inequalities, and you can only do inequalities on one field). IF there's a reason to search on an ID, yes it is PERFECTLY appropriate to store in the document as well - in fact, my wrapper library always does this.
the correct notation, btw, would be FieldPath.documentId() (method, not constant) - alternatively, __name__ - but I believe this only works in Queries. The reason it requested a new index is without the () it assumed you had a field named FieldPath with a subfield named documentid.
Further: FieldPath.documentId() does NOT generate the documentId at the server - it generates the FULL PATH to the document - see Firestore collection group query on documentId for a more complete explanation.
So net:
=> documentId's should be as random as possible within a collection; it's generally best to let Firestore generate them for you.
=> a valid exception is when you have ONE AND ONLY ONE sub-document under another - for example, every "user" document might have one and only one "forms of Id" document as a subcollection. It is valid to use the SAME ID as the parent document in this exceptional case.
=> anything you want to query should be a FIELD in a document,and generally simple fields.
=> WORD TO THE WISE: Firestore "arrays" are ABSOLUTELY NOT ARRAYS. They are ORDERED LISTS, generally in the order they were added to the array. The SDK presents them to the CLIENT as arrays, but Firestore it self does not STORE them as ACTUAL ARRAYS - THE NUMBER YOU SEE IN THE CONSOLE is the order, not an index. matching elements in an array (arrayContains, e.g.) requires matching the WHOLE element - if you store an ordered list of objects, you CANNOT query the "array" on sub-elements.
From what I've found:
FieldPath.documentId does not match on the documentId, but on the refPath (which it gets automatically if passed a document reference).
As such, since the documents are to be sorted by timestamp, it would be more ideal to create a timestamp fieldvalue for createdAt rather than a human-readable string which is prone to string length sorting over the value of the string.
From there, you can simply sort by date and limit to last. You can keep the document ID's as you intend.

Firebase queries and compound indexes

I have the following document structure in firebase:
{
typeId: number,
tripId: number,
locationId: string,
expenseId: number,
createtAt: timestamp
}
I want to query this collection using different 'where' statement everytime. Sometimes user wants to filter by type id and sometimes by locationId or maybe include all of the filters.
But it seems like I would need to create a compound index of each possible permutation? For example: typeId + expenseId, typeId + locationId, location + expenseId, etc, otherwise it doesn't work.
What if I have 20 fields and I want to make it possible to search across all of these?
Could you please help me to construct a query and indexes for the following requirement: Possibility to query across all fields, query can contain one, two, three, all or no fields included in where clause and always has to be ordered descending order by createdAt.
Cloud Firestore automatically creates indexes for the individual fields of your documents. So it can already filter on each field without you have to manually add these indexes.
In many cases it is able to combine these indexes to allow queries on field combinations, by performing a so-called zig-zag-merge-join.
Custom additional indexes are typically only needed once you add an ordering-clause to your query, in addition to filter clauses. If you have such a case, the Firestore client will log an error telling you exactly what index to create (with a link to the Firestore console that is prepopulated to created the index for you).

How can I query multiple fields on a single map data in Firestore?

I'm building an app using React + Redux + Firebase. In Firestore users collection, I have multiple fields including language, subject as map data. So for example,
// language that user can speak
language = {
english: true
}
// subjects that the user can teach
subject = {
math: true
science: true
}
In the main app, user can search other users by filtering subjects and languages. For example, user may look for the other users who can teach 'math' and 'science' using an 'english' language.
And I'm struggling with filtering multiple fields in map data. I could query for on field by doing ref.where('subject.${val}', '==' , true). But is there any way to query on multiple fields to get a document which contains a subject hash at any given number of subjects?
I tried to put data in array but currently firebase Array membership only support filtering one item in the array. So I guess it's a good start with storing in hash map. Any suggestion?
I tried to put data in array but currently firebase Array membership only support filtering one item in the array.
You're right, you can filter your items only by a single item that exist in an array. If you'll chain more than one function call, you'll get an error similar with this:
Invalid Query. Queries only support having a single array-contains filter.
And to answer your question:
But is there any way to query on multiple fields to get a document which contains a subject hash at any given number of subjects?
Unfortunately, there are no wildcards in Firestore. You have to identify the property names of your documents by their exact property name.
If you want to limit the results by filtering on multiple properties, you need to chain where() functions, like in the following example:
ref.where('subject.math', '==' , true)
.where('subject.science', '==' , true)
.where('language.english', '==' , true)

Firebase get data compare two fields

I'm trying to get all the documents that have my phone number as the fromNumber or the toNumber. My call right now is:
database.collection('documents').where('fromNumber','==',myPhoneNumber).get().then();
Instead of making 2 calls, one to check the fromNumber and the second one to check the toNumber, how can I check both at the same time and in the same .get()?
Btw: tested this code:
database.collection('documents')
.where('fromNumber','==',myPhoneNumber)
.where('toNumber','==',myPhoneNumber).get()
.then();
But it checks if both are true, it's an AND instead of the OR I'm looking for.
According to the official documentation, there a are some query limitations, when it comes to Firestore:
Cloud Firestore does not support the following types of queries:
Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
As suggested in the documentation, you should create two separate queries and merge the result cliend side.

Resources