Pablo Alejandro
Pablo Alejandro

Reputation: 607

ElasticSearch multiple queries in one

I am using ElasticSearch and I want to make a query.

I have differents modules: ['a', 'b', 'c', 'd']. where a and b have an extra value (companyId) I need to filter the text of all modules, but I need to filter the companyId just for a and b not for modules c and d.

This will look something like this:

SELECT * FROM my_table WHERE (modules in ('a', 'b') and companyId='myid') OR (modules in ('b', 'c'))

But I have this:

client.search({
      index: INDEX,
      type: TYPE,
      body: {
        query: {
          bool: {
            must: {
              match: { text: 'mytext' },
            },
            filter: [
              { terms: { module: ['a', 'b', 'c', 'd'] } },
              { term: { companyId: 'myid' } },
            ]
          }
        }
      }
    });

Thanks a lot if you can help.

Upvotes: 3

Views: 19774

Answers (1)

Kamal Kunjapur
Kamal Kunjapur

Reputation: 8860

The below query is what you are looking for. I've implemented the OR operator i.e. should inside the filter

{
  "query": {
    "bool": {
      "must": {
        "match": { "text": "mytext" }
      },
      "filter": [
       {
          "bool": {
            "should": [
              {
                "bool": {
                  "must": [
                      { "match": { "module": "a" }},
                      { "match": { "companyId": "1" }}
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                      { "match": { "module": "b" }},
                      { "match": { "companyId": "1" }}
                   ]
                }
              },
              {
                "bool": {
                  "must": {
                    "match": { "module": "c" }
                  }
                }
              },
              {
                "bool": {
                  "must": {
                    "match": { "module": "d" }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Upvotes: 10

Related Questions