Cloud Firestore's OrderBy query sorts data case-sensitively, resulting in discrepancies between expected and actual sorting behavior. For instance, data stored as "AAA" and "aaa" is sorted as "AAA", "BBB", "aaa", and "bbb", whereas the desired order is "AAA", "aaa", "BBB", and "bbb".
Cloud Firestore does not provide a built-in flag for case-insensitive sorting. The only effective solution is to store the sensitive field twice in the document. The first field, myData, stores the original data as is. The second field, myData_insensitive, stores a case-insensitive version of the data.
DocA: -> myData = 'AAA' -> myData_insensitive = 'AAA' DocB: -> myData = 'aaa' -> myData_insensitive = 'AAA' DocC: -> myData = 'BBB' -> myData_insensitive = 'BBB' DocD: -> myData = 'bbb' -> myData_insensitive = 'BBB'
Queries can now be executed on myData_insensitive, ensuring case-insensitive sorting. However, the original data is displayed by extracting the value from myData.
Case-folding becomes more complex when dealing with Unicode characters. Case insensitive sorting can vary across human languages, requiring additional processing to ensure consistent results. One approach is to normalize the data using caseFoldNormalize() and store the result in a separate field:
<code class="javascript">caseFoldNormalize = function (s){ return s.normalize('NFKC').toLowerCase().toUpperCase().toLowerCase() }; caseFoldDoc = function(doc, field_options) { // Case fold desired document fields if (field_options != null) { for (var field in field_options) { if (field_options.hasOwnProperty(field)) { switch(field_options[field]) { case 'case_fold': if (doc.hasOwnProperty(field) && Object.prototype.toString.call(doc[field]) === "[object String]") { doc[field.concat("_insensitive")] = caseFoldNormalize(doc[field]) } break; } } } } return doc; }</code>
Despite being an effective workaround, it is important to note that this approach involves additional storage and processing overhead, which should be considered when implementing it in production applications.
The above is the detailed content of How to Enable Case Insensitive Sorting in Cloud Firestore?. For more information, please follow other related articles on the PHP Chinese website!