如何使用Java API使用Elasticsearch FunctionScore查询

时间:2016-04-13 05:50:29

标签: java elasticsearch java-api

我需要使用Java API实现下面的function_score查询。我在elasticsearch

的Java API部分找不到任何关于function_score查询的官方文档
{
  "size": 40,
  "query": {
    "function_score": {
      "functions": [
        {
          "gauss": {
            "location": {
              "origin": {
                "lat": 39.99606,
                "lon": 116.480484
              },
              "offset": "2km",
              "scale": "3km"
            }
          }
        }
      ],
      "score_mode": "sum",
      "boost_mode": "replace",
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "startTime": {
                  "from": "2016-04-12T12:00:00.000Z",
                  "to": "2016-04-12T16:00:00.000Z",
                  "include_lower": true,
                  "include_upper": true
                }
              }
            },
            {
              "range": {
                "endTime": {
                  "from": "2016-04-12T12:00:00.000Z",
                  "to": "2016-04-12T16:00:00.000Z",
                  "include_lower": true,
                  "include_upper": true
                }
              }
            }
          ]
        }
      }
    }
  }
}

我像这样使用Java api

RangeQueryBuilder queryStartDate = QueryBuilders.rangeQuery("startTime").gte(param.getStartTime())
                .lte(param.getEndTime());

        RangeQueryBuilder queryEndDate = QueryBuilders.rangeQuery("endTime").gte(param.getStartTime())
                .lte(param.getEndTime());

// query
QueryBuilder querys = QueryBuilders.boolQuery().must(queryStartDate).must(queryEndDate);

// function
Map<String, Double> locationMap = new HashMap<String, Double>();
        locationMap.put("lat", param.getLat());
        locationMap.put("lon", param.getLng());
        ScoreFunctionBuilder sfb2 = ScoreFunctionBuilders.gaussDecayFunction("location", locationMap, "1km")
                .setOffset("2km");

//function_score
FunctionScoreQueryBuilder sa = new FunctionScoreQueryBuilder().boostMode("replace").add(sfb2);

//final search
SearchResponse response = client.prepareSearch().setIndices("film").setTypes("data").setQuery(sa)
                .setQuery(querys).setSize(40).execute().actionGet();

但它不起作用

2 个答案:

答案 0 :(得分:3)

您需要在FunctionScoreQueryBuilder中添加查询,如下所示:

    FunctionScoreQueryBuilder fqBuilder = QueryBuilders.functionScoreQuery(querys);
    fqBuilder.boostMode(CombineFunction.REPLACE);
    fqBuilder.scoreMode(ScoreMode.Sum.name().toLowerCase());
    fqBuilder.add(sfb2);
    SearchResponse response = client.prepareSearch().setIndices("film").setTypes("data").setQuery(fqBuilder).setSize(40).execute().actionGet();

答案 1 :(得分:2)

在ElasticSearch 5.x中,这已经改变了,并且FunctionScoreQueryBuilder.add()方法不再存在(已删除,未弃用)。此页面有一些示例:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-compound-queries.html#java-query-dsl-function-score-query