我试图找出如何构建针对弹性搜索的查询,其中查询值存在于2个字段值的范围之间。
假设我有一个模板
{
"template": "addresses",
"mappings": {
"addresses": {
"properties": {
"street_number_1": { "type": "integer" },
"street_number_2": { "type": "integer" },
... //other unimportant fields
}
}
}
根据上述定义,如果我的地址为100-120 High Street,其中street_number_1为100而street_number_2为120,如果我要执行112 High Street的搜索,则该记录应该按原样返回在100到120之间。什么样的弹性搜索功能/查询可以让我这样做?
答案 0 :(得分:1)
您有两种选择。使用当前映射,您可以使用两个range queries,如下所示:
private void getPhotos(){
Log.d(TAG, "getPhotos: getting photos");
Log.d(TAG, "getPhotos: getting jobs count first count = " + mJobs.size() );
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_jobs))
.child("United States")
.child("Web Development")
.orderByKey();
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
PostJob job = new PostJob();
Log.d(TAG, "onDataChange: getJOBS " + singleSnapshot.getValue());
Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();
//job.setUser_country(objectMap.get("user_country").toString());
job.setJob_headline(objectMap.get("job_headline").toString());
job.setJob_desc(objectMap.get("job_desc").toString());
job.setBudget(objectMap.get("budget").toString());
job.setTime_frame(objectMap.get("time_frame").toString());
//job.setTags(objectMap.get(getString(R.string.field_tags)).toString());
//job.setPhoto_id(objectMap.get(getString(R.string.field_photo_id)).toString());
//job.setUser_id(objectMap.get(getString(R.string.field_user_id)).toString());
//job.setDate_posted(objectMap.get("date_posted").toString());
//job.setImage_path(objectMap.get(getString(R.string.field_image_path)).toString());
/*
// soon going to be the proposals
ArrayList<Comment> comments = new ArrayList<Comment>();
for (DataSnapshot dSnapshot : singleSnapshot
.child(getString(R.string.field_comments)).getChildren()){
Comment comment = new Comment();
comment.setUser_id(dSnapshot.getValue(Comment.class).getUser_id());
comment.setComment(dSnapshot.getValue(Comment.class).getComment());
comment.setDate_created(dSnapshot.getValue(Comment.class).getDate_created());
comments.add(comment);
}
photo.setComments(comments);*/
mJobs.add(job);
}
Log.d(TAG, "onDataChange: jobs count = " + mJobs.size());
if( mJobs.size()>0){
//display our photos
displayPhotos();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
第二个选项涉及更改映射以使用integer range作为街道号码。像这样定义您的街道号码映射:
{
"query": {
"bool": {
"filter": [
{
"range": {
"street_number_1": {
"lte": 112
}
}
},
{
"range": {
"street_number_2": {
"gte": 112
}
}
}
]
}
}
}
然后将您的地址文档编入索引:
PUT addresses
{
"mappings": {
"_doc": {
"properties": {
"street_number": {
"type": "integer_range"
}
}
}
}
}
最后像这样查询:
PUT addresses/_doc/1
{
"street_number" : {
"gte" : 100,
"lte" : 120
}
}