ElasticSearch在过滤​​时忽略排序

时间:2013-07-15 16:07:37

标签: elasticsearch

ElasticSearch版本:0.90.1,JVM:1.6.0_51(20.51-b01-457)

我正在尝试使用我的ElasticSearch查询做两件事:1)根据布尔值(可搜索)和“open_date<明天”过滤结果,2)按字段“open_date”DESC

这会产生以下查询:

{
  "query": {
    "bool": {
      "should": [
        {
          "prefix": {
            "name": "foobar"
          }
        },
        {
          "query_string": {
            "query": "foobar"
          }
        },
        {
          "match": {
            "name": {
              "query": "foobar"
            }
          }
        }
      ],
      "minimum_number_should_match": 1
    },
    "filtered": {
      "filter": {
        "and": [
          {
            "term": {
              "searchable": true
            }
          },
          {
            "range": {
              "open_date": {
                "lt": "2013-07-16"
              }
            }
          }
        ]
      }
    }
  },
  "sort": [
    {
      "open_date": "desc"
    }
  ]
}

但是,返回的结果不是按“open_date”排序的。如果我删除过滤器:

{
  "query": {
    "bool": {
      "should": [
        {
          "prefix": {
            "name": "foobar"
          }
        },
        {
          "query_string": {
            "query": "foobar"
          }
        },
        {
          "match": {
            "name": {
              "query": "foobar"
            }
          }
        }
      ],
      "minimum_number_should_match": 1
    }
  },
  "sort": [
    {
      "open_date": "desc"
    }
  ]
}

......结果按预期回来。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

我不确定Tire代码,但JSON没有正确构建过滤后的查询。我的猜测是,这会溢出并导致sort元素也无法正确解析。

过滤后的查询应该像这样构建(参见http://www.elasticsearch.org/guide/reference/query-dsl/filtered-query/):

{
   "query": {
      "filtered": { // Note: this contains both query and filter
         "query": {
            "bool": {
               "should": [
                  {
                     "prefix": {
                        "name": "foobar"
                     }
                  },
                  {
                     "query_string": {
                        "query": "foobar"
                     }
                  },
                  {
                     "match": {
                        "name": {
                           "query": "foobar"
                        }
                     }
                  }
               ],
               "minimum_number_should_match": 1
            }
         },
         "filter": {
            "and": [
               {
                  "term": {
                     "searchable": true
                  }
               },
               {
                  "range": {
                     "open_date": {
                        "lt": "2013-07-16"
                     }
                  }
               }
            ]
         }
      }
   },
   "sort": [
      {
         "open_date": "desc"
      }
   ]
}

干杯, 波阿斯