Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elastic search must match if type exists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading