Home > Enterprise >  Elastic search must match if type exists
Elastic search must match if type exists

Time:10-21

I have this elastic search function that match two conditions. But now "type" is optional and I want return all cookies if type is not set and if type is set I want the same result as in the query below. Type is an enum (if that matters).

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))
})

This might be a super trivial thing but this is the first time I am using elastic search and I am super confused.

CodePudding user response:

I would check the Elastic documentation for an available option, but you can also come up with a conditional statement along these lines:

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))
})

CodePudding user response:

You can use a should clause , which will return a document if any of the clause is satisfied. I have used 2 queries in should

  1. must not exists- which will return documents which don't have a field set
  2. match - which will return document which have matching type values

further you can use must/filter - to return documents with match cookie id and which satisfy any of should clause.

use filter if you are just filtering. Filter does not calculate score so it is faster.

{
  "query": {
    "bool": {
      "minimum_should_match": 1, 
      "should": [
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "title"
              }
            }
          }
        },
        {
            "match": { type }
        }
      ],
      "must": [
        {
           "match": { 'cookie.id': cookie }
        }
      ]
    }
  }
}
  • Related