java lower firestore查询在搜索文档中的子字符串时读取
我有一个firestore
集合,其结构如下:
在我的一个活动中,我有一个搜索字段,用户在其中键入内容,我在recyclerView
中提供一些结果
现在,为了向用户提供结果,我查询我的收藏,并使用以下代码进行查询:
atv_Search.addTextChangedListener( new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() > 0) {
String[] words = s.toString().trim().split( "\\s+" );
for (int i = 0; i < words.length; i++) {
String Word = words[i];
words[i] = Word.substring( 0, 1 ).toUpperCase() + Word.substring( 1 );
}
s = TextUtils.join( " ", words );
db.collection( "Books" )
.whereArrayContains( "BookTitleArray", s.toString() ).limit( 20 ).get()
.addOnCompleteListener( task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
List<String> nameWords = (List<String>) document.get( "BookTitleArray" );
String name = TextUtils.join( " ", nameWords );
autoBookNames.add( name );
}
}
} );
db.collection( "Books" )
.whereGreaterThanOrEqualTo( "BookTitle", s.toString() ).whereLessThanOrEqualTo( "BookTitle", s.toString() + "\uF7FF" ).limit( 20 ).get()
.addOnCompleteListener( task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String name = document.getString( "BookTitle" );
autoBookNames.add( name );
}
}
} );
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
new CountDownTimer( 1000, 500 ) {
public void onFinish() {
Set<String> set = new LinkedHashSet<>( autoBookNames );
autoBookNames.clear();
autoBookNames.addAll( set );
adapter = new AutoCompleteAdapter( getApplicationContext(), R.layout.item_auto_search, R.id.item_drop, autoBookNames, false );
atv_Search.setAdapter( adapter );
if (!autoBookNames.isEmpty() && notSelected) {
atv_Search.showDropDown();
}
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
} );
现在,代码运行良好,但性能不是我想要的
通过使用这段代码,用户输入的每一个字母,我都会从数据库中执行40次读取(最终导致大量读取):
- 为了使用第二个查询查看字符串是否包含子字符串,我使用了20次读取李>
- 通过检查数组是否包含一个单词,我使用了另外20次读取李>
我当然可以取消限制(20个),但我可能会遇到更大的问题,因为我收集了数千份文档
有更聪明的方法吗?我能不能改进一下,这样就不会每封信都读40遍
谢谢!
共 (0) 个答案