简体   繁体   English

nodejs或nestjs中基于条件的elasticsearch方法

[英]elastic search method based on condition in nodejs or nestjs

Hello I am implementing elasticsearch using nestjs .您好,我正在使用nestjs

Currently, I am trying to add match keywords according to each condition, but I am having difficulties, so I leave a question.目前,我正在尝试根据每个条件添加匹配关键字,但我遇到了困难,所以我留下了一个问题。

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 *') + '*',
                },
              },
            ],
          },
        },
      },
    });

In the code above, keyword is a variable that may or may not exist.在上面的代码中, keyword是一个可能存在也可能不存在的变量。

But I am getting an error in the above code, how should I set the condition?但是我在上面的代码中遇到错误,我应该如何设置条件?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM