如何在ElasticSearch中组合多个查询

时间:2012-11-12 21:49:26

标签: coffeescript elasticsearch hubot

这里是参考代码。我正在尝试制作一个hubot插件,记录到elasticsearch,然后使用hubot命令搜索这些日志。

https://gist.github.com/4050748

我正在尝试检索与两个查询匹配的记录。

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

我在期待:

  • 最多50条记录
  • 具有给定用户的记录
  • 过去一小时的记录

我得到了:

  • 最多10条记录
  • 具有给定用户的记录
  • 随时

如何在过去一小时内获取所有带有用户名的记录?我是否需要将match_all与过滤器一起使用?我试图不受支持吗?

在SQL中它将类似于:

Select (*) from messages where user_name = ? and time > ?

2 个答案:

答案 0 :(得分:16)

对于那些偶然发现这个问题的人,并想知道在ElasticSearch中组合匹配和范围查询是什么样子,这个例子看起来像

curl 'localhost:9200/<index>/_search?pretty=true' -d '{
  "query" : {
    "bool": {
      "must": [
        {
          "match": {
            "user": "SomeUsername"
          }
        },
        {
          "range" : {
            "date": {
              "gt": "now-1h"
            }
          }
        }
      ]
    }
  }
}'

答案 1 :(得分:15)

您需要使用bool query将不同的查询组合在一起。然后,您可以选择每个查询是否必须匹配,是否匹配(可选)或必须匹配。