Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine multiple queries in ElasticSearch

For reference here is the code. I am trying to make a hubot plugin that logs to elasticsearch and then uses hubot commands to search those logs.

https://gist.github.com/4050748

I am trying to retrieve records that match two queries.

{ 
  query: { 
        match: {
          user: "SomeUsername" 
        }, 
        range: {
          date: {
            from: (Date.now() - 3600) 
          }
        }
  },
  size: 50 
}

I was expecting:

  • Up to 50 records
  • records that had the given user
  • records in the last hour

I got:

  • up to 10 records
  • records that had the given user
  • from any time

How do I get all the records with some username in the last hour? Do I need to use match_all with filters? Is what I am attempting unsupported?

In SQL it would be something like:

Select (*) from messages where user_name = ? and time > ?
like image 960
EnabrenTane Avatar asked Nov 12 '12 21:11

EnabrenTane


People also ask

How do I merge two queries in Elasticsearch?

You can combine the queries using bool query. Based on your requirement you can use 'should' or 'must' inside the bool clauses.

Can Elasticsearch do joins?

Joining queriesedit Instead, Elasticsearch offers two forms of join which are designed to scale horizontally. Documents may contain fields of type nested . These fields are used to index arrays of objects, where each object can be queried (with the nested query) as an independent document.

What are compound queries?

Compound queries are used when you want to combine the results of two other queries to come up with a new set of results.


2 Answers

For anyone who stumbles on this question and wonders what it looks like to combine a match and range query in ElasticSearch, this example would look like

curl 'localhost:9200/<index>/_search?pretty=true' -d '{
  "query" : {
    "bool": {
      "must": [
        {
          "match": {
            "user": "SomeUsername"
          }
        },
        {
          "range" : {
            "date": {
              "gt": "now-1h"
            }
          }
        }
      ]
    }
  }
}'
like image 180
Cody A. Ray Avatar answered Oct 17 '22 08:10

Cody A. Ray


You need to use the bool query to combine different queries together. You can then choose whether each single query must match, should match (optional), or must not match.

like image 17
javanna Avatar answered Oct 17 '22 08:10

javanna