alex.bour
alex.bour

Reputation: 2964

ElasticSearch build query depending a condition

I want to know if it's possible to build a query depending some conditions in my code.

self.search(query: {
                    bool: {
                      must: [
                        { term: { country_id: country_id }},
                        { term: { region_id: region_id }} => if region_id is not nil
]
                    }
                  }

In this example, I would like to add the line:

{ term: { region_id: region_id }}

ONLY if region_id is not nil/ present in my method.

In SQL I can build a query with multilines and conditions. Can I do the same with ES ?

Info: working in ruby here

Thanks

Upvotes: 1

Views: 87

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

You'll want to create a query variable to build the query, and conditionally add the elements (terms) that you want. Give this a try:

# Start with a base search definition
query = { 
  query: {
    bool: {
      must: [
        { term: { country_id: country_id }}
      ]
    }
  }
}

# Conditionally add search terms
if region_id is not nil
  query[:query][:bool][:must] << { term: { region_id: region_id }}
end

# Execute the search
self.search(query)

Upvotes: 2

Related Questions