如果类型存在,ElasticSearch必须匹配

ghhaqwfi  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(2)|浏览(174)

我有一个ElasticSearch函数,可以匹配两个条件。但是现在“type”是可选的,如果没有设置type,我希望返回所有cookie,如果设置了type,我希望得到与下面查询相同的结果。Type是一个枚举(如果这很重要的话)。

export const searchCookies: HttpFunction = enrichCloudFunction(async (req, res) => {
  const {
    query: { type, cookies, from, size },
  } = validateCookieQuery(req)
  const {
    hits: { hits },
  } = await elastic.search<ExtendedStuff>({
    from: from || 0,
    index: cookieIndex({ prefix: config.prefix }),
    query: {
      bool: {
        must: [
          {
            match: { 'cookie.id': cookie },
          },
          {
            match: { type },
          },
        ],
      },
    },
    size: size || 20,
  })

  res.json(hits.map((x) => x._source))
})

这可能是一个超级琐碎的事情,但这是我第一次使用ElasticSearch,我是超级困惑。

c2e8gylq

c2e8gylq1#

我会查看Elastic文档中的可用选项,但您也可以按照以下方式提出一个条件语句:

export const searchCookies = enrichCloudFunction(async (req, res) => {
  const { query: { type, cookies, from, size } } = validateCookieQuery(req)
  const boolOptions = {
    must: [ { match: { 'cookie.id': cookie } } ]
  }
  if ( type ){
    boolOptions.must.push({ match: { type }})
  }
  const { hits: { hits } } = await elastic.search<ExtendedStuff>({
    from: from || 0,
    index: cookieIndex({ prefix: config.prefix }),
    query: { bool: boolOptions },
    size: size || 20,
  })
  res.json(hits.map((x) => x._source))
})
2uluyalo

2uluyalo2#

您可以使用should clause,如果满足任何子句,它将返回一个文档。
1.不能存在-这将返回没有字段集的文档

  1. match -将返回具有匹配类型值文档
    此外,您可以使用must/filter -返回具有匹配cookie id且满足任何should子句文档。
    如果您只是在筛选,请使用筛选器。2筛选器不计算分数,因此速度更快。
{
  "query": {
    "bool": {
      "minimum_should_match": 1, 
      "should": [
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "title"
              }
            }
          }
        },
        {
            "match": { type }
        }
      ],
      "must": [
        {
           "match": { 'cookie.id': cookie }
        }
      ]
    }
  }
}

相关问题