一种基于节点或嵌套内条件ElasticSearch方法

0vvn1miw  于 2022-11-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(99)

你好,我正在使用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是一个变量,它可能存在,也可能不存在。
但是我在上面的代码中得到了一个错误,我应该如何设置条件?

4sup72z8

4sup72z81#

const query = [];
if(keyword){
   query.push({
      query_string:{
         query : xxx
      }
   })
}

const { hits } = await this.elasticsearchService.search({
      index: 'myindex',
      body: {
        query: {
          bool: {
            must: query
          },
        },
      },
    });

相关问题