基于nodejs或nestjs中条件的弹性搜索方法



您好,我正在使用nestjs实现elasticsearch。

目前,我正在尝试根据每个条件添加匹配关键字,但我有困难,所以我留下了一个问题。

const { hits } = await this.elasticsearchService.search({
index: 'myindex',
body: {
query: {
bool: {
must: [
{
match: {
type: type.join(' or '),
},
},
keyword && {
query_string: {
query:
'*' + keyword.replace(/ /g, '* AND *') + '*',
},
},
],
},
},
},
});

在上面的代码中,keyword是一个可能存在也可能不存在的变量。

但是我在上面的代码中得到一个错误,我应该如何设置条件?

const query = [];
if(keyword){
query.push({
query_string:{
query : xxx
}
})
}
const { hits } = await this.elasticsearchService.search({
index: 'myindex',
body: {
query: {
bool: {
must: query
},
},
},
});

最新更新