Find replicated docs cblite - android

How to find out whether a document from a cblite database has been replicated on android with the help of cblite api?
Came across this link but couldn't make any sense out of it.
Pouchdb. How to verify a doc is replicated

In cblite db each document has a sequence number, whenever each document gets replicated a sequence number is assigned to the document. Here's piece of code to get a better understanding,
//Get the latest sequence number of the document replicated
lastSeq = rep.getLastSequence();
Query query = database.createAllDocumentsQuery();
QueryEnumerator rowEnum = query.run();
for (Iterator<QueryRow> it = rowEnum; it.hasNext();) {
QueryRow row = it.next();
if(lastSequence!=null)
{
if(Long.parseLong(lastSequence)>=row.getSequenceNumber())
{
purgeDoc = row.getDocument();
purgeDoc.purge();
}
}
}

Related

how can i count the number of document from firestore and return it in a text [duplicate]

I want to calculate how many documents are in a collection, not the length of the document. I have tried it with some code but what appears is the length of the character from my document name.
this my code :
StreamSubscription<DocumentSnapshot> userpost;
final DocumentReference documentReference =
Firestore.instance.document("product/$documentPost");
userpost = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.exists) {
for (int i = 0; i < datasnapshot.data.length; i++){
print(datasnapshot.data.length);
}
An Example Function to fetch Documents Count.
void countDocuments() async {
QuerySnapshot _myDoc = await Firestore.instance.collection('product').getDocuments();
List<DocumentSnapshot> _myDocCount = _myDoc.documents;
print(_myDocCount.length); // Count of Documents in Collection
}
You can use the count() function which was added in cloud_firestore version 4.0.0
Accepted answer might be a bad solution because you have to fetch all the documents just to count the number of documents. As per Firestore pricing, every document read is taken as 1 read count.
So a better solution is to use the count() function instead.
AggregateQuerySnapshot query = FirebaseFirestore.instance.collection('random_collection').count().get();
int numberOfDocuments = query.count;
count() is an Aggregation Query
PS: You might need to update your firebase plugins in pubspec.yaml.
With Cloud Firebase 2.0, there is a new way to count documents in a collection. According to reference notes, the count does not count as a read per document but a metaData request:
"[AggregateQuery] represents the data at a particular location for retrieving metadata without retrieving the actual documents."
Example:
final CollectionReference<Map<String, dynamic>> userList = FirebaseFirestore.instance.collection('users');
Future<int> countUsers() async {
AggregateQuerySnapshot query = await userList.count().get();
debugPrint('The number of users: ${query.count}');
return query.count;
}

How to count the number of documents firestore on flutter?

I want to calculate how many documents are in a collection, not the length of the document. I have tried it with some code but what appears is the length of the character from my document name.
this my code :
StreamSubscription<DocumentSnapshot> userpost;
final DocumentReference documentReference =
Firestore.instance.document("product/$documentPost");
userpost = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.exists) {
for (int i = 0; i < datasnapshot.data.length; i++){
print(datasnapshot.data.length);
}
An Example Function to fetch Documents Count.
void countDocuments() async {
QuerySnapshot _myDoc = await Firestore.instance.collection('product').getDocuments();
List<DocumentSnapshot> _myDocCount = _myDoc.documents;
print(_myDocCount.length); // Count of Documents in Collection
}
You can use the count() function which was added in cloud_firestore version 4.0.0
Accepted answer might be a bad solution because you have to fetch all the documents just to count the number of documents. As per Firestore pricing, every document read is taken as 1 read count.
So a better solution is to use the count() function instead.
AggregateQuerySnapshot query = FirebaseFirestore.instance.collection('random_collection').count().get();
int numberOfDocuments = query.count;
count() is an Aggregation Query
PS: You might need to update your firebase plugins in pubspec.yaml.
With Cloud Firebase 2.0, there is a new way to count documents in a collection. According to reference notes, the count does not count as a read per document but a metaData request:
"[AggregateQuery] represents the data at a particular location for retrieving metadata without retrieving the actual documents."
Example:
final CollectionReference<Map<String, dynamic>> userList = FirebaseFirestore.instance.collection('users');
Future<int> countUsers() async {
AggregateQuerySnapshot query = await userList.count().get();
debugPrint('The number of users: ${query.count}');
return query.count;
}

Firestore whereEqualsTo from arraylist

I'm trying to list documents that matches field String value from ArrayList.
Simply:
I have ArrayList with tags stored at runtime
and documents with field tag
and I want to query documents that matches tag with one of tags stored in ArrayList. Is this possible with official query or does I have to download all documents and filter it client-side? Thanks for any answers.
Also, this is my method generating query:
public static Query getQueryForFollowed(DocumentSnapshot snapshots) {
if (snapshots == null || !snapshots.exists()) {
return FirebaseFirestore.getInstance().collection("posts").whereEqualTo("null", "null"); // return query that will get nothing
}
ArrayList<String> f = processFollowedTags(snapshots);
Query query = FirebaseFirestore.getInstance()
.collection("posts")
.whereEqualTo("tag", f.get(0));
for (int i = 1; i < f.size(); i++) {
query = query.whereEqualTo("tag", f.get(i));
}
return query;
}
I have debugged code and query has contained requested conditions, but query didn't found any document matching it.
Try This
Query query = FirebaseFirestore.getInstance()
.collection("posts")
.whereEqualTo("tag", f.get(0)).orderBy("tag", Query.Direction.ASCENDING);;
After some more search on Google I have found that querying field to multiple values is not available.
According to:
https://stackoverflow.com/a/46633294/8428193
https://github.com/firebase/firebase-js-sdk/issues/321
Below code snippet may help you.
fun arrayContainsQueries() {
// [START array_contains_filter]
val citiesRef = db.collection("cities")
citiesRef.whereArrayContains("regions", "west_coast")
// [END array_contains_filter]
}
ref : git
As of Nov 2019 this is now possible to do with the in query.
With the in query, you can query a specific field for multiple values
(up to 10) in a single query. You do this by passing a list containing
all the values you want to search for, and Cloud Firestore will match
any document whose field equals one of those values.
it would look like this:
Query query = FirebaseFirestore.getInstance()
.collection("posts")
.whereIn("tag", f);

Couchbase Lite: reading document vs querying data

I'm switching an Android project to using Couchbase Lite, and I'm confused with ways for fetching the data from the database.
I have a document, which contains only one property:
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("data_key", json);
Document document = database.getDocument("data_doc_id");
document.putProperties(properties);
The next my step is getting the stored data from the database. I found two ways:
The first approach is reading the document
Document doc = database.getDocument("data_doc_id");
String json = (String) doc.getProperty("data_key");
The second one is querying
View view = database.getView("data_json");
view.setMap(new Mapper() {
#Override
public void map(Map<String, Object> document, Emitter emitter) {
if ("data_doc_id".equals(document.get("_id")) {
String json = (String) doc.getProperty("data_key");
emitter.emit("data_key", json);
}
}
}, "1.0");
QueryEnumerator queryEnumerator = view.createQuery().run();
String dataJson = "";
for (QueryRow queryRow : run) {
if ("data_key".equals(queryRow.getKey()) {
json = (String) queryRow.getValue();
}
}
Is it okay to use the first approach to get the stored JSON?
For what cases the second approach should be used? It has far more code than the first one, maybe it has something to do with caching or/and speed/performance? What are the pros and cons of this approach?
The first approach is retrieving the document directly. This is the fastest way to do it.
With databases, though, often you want to retrieve documents based on some feature of the data. To do this you want the ability to create queries about the data. That's what the second approach is for.

How to efficiently manage search suggestion using Android QSB?

I try to make a dictionary using Quick Search Box in Android. As shown in the SearchableDictionary tutorial, it loads all (999 definitions)data and uses them as matches to the input text to get the search suggestion. in my case, I have 26963 rows of data that need to be suggest while user input a word on QSB. therefore, I want to grab the char data one by one from the QSB, so that it will be efficiently load necessary suggestion. how can i do this?
here's the code i use...
bringit(200);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// from click on search results
//Dictionary.getInstance().ensureLoaded(getResources());
String word = intent.getDataString();
//if(word.length() > 3){bringit(10);}
Dictionary.Word theWord = Dictionary.getMatches(word).get(0);
launchWord(theWord);
finish();
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//SearchManager.
//String bb =
mTextView.setText(getString(R.string.search_results, query));
WordAdapter wordAdapter = new WordAdapter(Dictionary.getMatches(query));
//letsCount(query);
mList.setAdapter(wordAdapter);
mList.setOnItemClickListener(wordAdapter);
}
Log.d("dict", intent.toString());
if (intent.getExtras() != null) {
Log.d("dict", intent.getExtras().keySet().toString());
}
}
private void letsCount(String query) {
// TODO Auto-generated method stub
for(int i=0; i<query.length(); i++){
definite[i] = query.charAt(i);
}
}
public void bringit(int sum) {
// TODO Auto-generated method stub
String[] ss = new String[10];
Log.d("dict", "loading words");
for(int i=1; i<=sum; i++){
KamusDbAdapter a = new KamusDbAdapter(getApplicationContext());
a.open();
Cursor x = a.quick(String.valueOf(i));startManagingCursor(x);
if(x.moveToFirst()){
ss[0] = x.getString(1);
ss[1] = x.getString(2);
}
Dictionary.addWord(ss[0].trim(), ss[1].trim());
Log.v("Debug",ss[0]+" "+ss[1]);
//onStop();
}
}
I use SQLite to collect data. and the other code is just same as the tutorial...
Retrieving a cursor is generally slow. You only want to retrieve one cursor which contains all the matching results.
You should perform the searching using SQL rather than fetching everything. A FULL_TEXT search is usually fastest for text matching, it is however slightly more complicated to implement than a simple LIKE, but I highly recommend you give it a try.
So you want to execute an SQL statement like:
SELECT * FROM my_table WHERE subject_column MATCH 'something'
See SQLite FTS Extension for more information. You can also use wild-cards to match part of a word.
In terms of search suggestions there is really no point returning more than around ~100 results since generally no users ever bother to scroll down that far, so you can further speed things up by adding a LIMIT 0, 100 to the end of your SQL statement.
If possible only start getting cursors once the user has entered more than X number of characters (usually 3 but in you're case this may not be appropriate). That way you're not performing searches that could potentially match thousands of items.
You seem to be leaving lots of cursors open until the application closes them even though you don't actually need them anymore: instead of calling startManagingCursor just make sure to call x.close() after your if (x.moveToFirst()) { ... } - this will free up memory faster.
On an unrelated note: please don't name your variables and methods things like ss or bringIt() as it makes code hard to read -- what is ss and what does bringIt() bring exactly?
You could have a look at the full text search extension in SQL Lite. Idea is to have a SQL query that fetches only the matching results, not all the results and then filter.
There is also a sample for the Android SDK: com/example/android/searchabledict/DictionaryDatabase

Categories

Resources