如何使用Firestore数据实施应用内文本搜索?

时间:2019-03-06 10:00:23

标签: java android firebase google-cloud-firestore full-text-search

你好,朋友们!

我需要在我的android应用中实现全文搜索,我正在寻找最佳方法。

我发现执行此操作的方法很少,但我正在寻求一种建议,这将是最好的方法,并且可以减少问题。我有一个完整的数据集,其中包含HTML文本,查询后我将其解析,然后将其显示。我需要在此集合中实施全文搜索。 我找到了推荐的 Algolia文本搜索,但这并不是我真正需要的。 或者也许我可以根据Firestore文档从连接离线时缓存数据的缓存中搜索文本?

是否可以查询所有数据,然后将其存储在ArrayList或Array中,或者什么是最佳选择?

这是我的viewModel,用于查询整个集合。

public class DetailActivityViewModel extends ViewModel {

private final FirebaseListLiveData<Data> liveDataQuery;

public DetailActivityViewModel(String id) {
    liveDataQuery = new FirebaseListLiveData<>(Data.class, FirebaseFirestore.getInstance()
            .collection("fullData").whereEqualTo("mainId", id)
            .orderBy("order", Query.Direction.ASCENDING));
}
public FirebaseListLiveData<Data> getLiveDataQuery() {
    return liveDataQuery;
}
}

最后是我的自定义LiveData。

public class FirebaseListLiveData<T> extends LiveData<List<T>> implements EventListener<QuerySnapshot> {

private Class<T> typeParameter;
private Query query;
private ListenerRegistration listenerRegistration;

public FirebaseListLiveData(Class<T> typeParameter, Query query) {
    this.typeParameter = typeParameter;
    this.query = query;
}
@Override
protected void onActive() {
    if (listenerRegistration == null) {
        listenerRegistration = query.addSnapshotListener(this);
    }
}
@Override
protected void onInactive() {
    if (listenerRegistration != null) {
        listenerRegistration.remove();
        listenerRegistration = null;
    }
}

@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
    if (e == null) {
        if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
            postValue(queryDocumentSnapshots.toObjects(typeParameter));
        } else {
            postValue(null);
        }
    } else {
        postValue(null);
    }
}
}

0 个答案:

没有答案