Query to get exact matches of Elastic Field with multile values in Array

时间:2015-10-06 08:44:50

标签: r elasticsearch

I want to write a query in Elastic that applies a filter based on values i have in an array (in my R program). Essentially the query:

  1. Matches a time range (time field in Elastic)
  2. Matches "trackId" field in Elastic to any value in array oth_usr
  3. Return 2 fields - "trackId", "propertyId"

I have the following primitive version of the query but do not know how to use the oth_usr array in a query (part 2 above).

query <- sprintf('{"query":{"range":{"time":{"gte":"%s","lte":"%s"}}}}',start_date,end_date)
view_list <- elastic::Search(index = "organised_recent",type = "PROPERTY_VIEW",size = 10000000,
                             body=query, fields = c("trackId", "propertyId"))$hits$hits

2 个答案:

答案 0 :(得分:0)

您需要添加terms个查询,并将range一个查询嵌入到bool/must查询中。尝试更新您的查询,如下所示:

terms <- paste(sprintf("\"%s\"", oth_usr), collapse=", ")
query <- sprintf('{"query":{"bool":{"must":[{"terms": {"trackId": [%s]}},{"range": {"time": {"gte": "%s","lte": "%s"}}}]}}}',terms,start_date,end_date)

答案 1 :(得分:0)

我不熟练使用R语法,但这是原始的JSON查询。

它会检查您的time字段是否与给定范围(start_timeend_time)匹配,以及您的terms完全匹配trackId是否匹配。

根据您的要求,它仅返回trackIdpropertyId个字段:

POST /indice/_search
{
  "_source": {
    "include": [
      "trackId",
      "propertyId"
    ]
  },
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "time": {
              "gte": "start_time",
              "lte": "end_time"
            }
          }
        },
        {
          "terms": {
            "trackId": [
              "terms"
            ]
          }
        }
      ]
    }
  }
}