我正在尝试使用query_string和星号(query: `${city}*`
)搜索城市,同时还要通过countryId
过滤结果。
该查询在不对countryId进行过滤的情况下也能很好地工作,但是在添加过滤器时却什么也没找到。 Boty city
和countryId
被映射为text
。
代码:
const elasticsearch = require('elasticsearch');
...
this.client = new elasticsearch.Client({
hosts: [this._serviceUri]
});
...
// The interesting part:
const results = await this.client.search({
index: 'cities',
body: {
query: {
query_string: {
query: `${city}*`,
fields: ['city', 'countryId'],
// type: 'best_fields'
}
},
post_filter: { term: { countryId } }
}
});
如何使用post_filter或类似的东西正确过滤结果?
更新: 映射如下所示:
mappings: {
_doc: {
properties: {
"city": {type: 'text'},
"countryId": {type: 'text'}
}
}
}
答案 0 :(得分:1)
我会这样做,而无需诉诸post_filter
:
// The interesting part:
const results = await this.client.search({
index: 'cities',
body: {
query: {
bool: {
must: {
query_string: {
query: `${city}*`,
fields: ['city', 'countryId'],
// type: 'best_fields'
}
},
filter: {
term: {
countryId: `${countryId}`,
}
}
}
}
}
});