如何使用Elasticsearch 5.2.2搜索突出显示使用Java API

时间:2017-04-03 16:20:27

标签: java elasticsearch highlight

让Elasticsearch Java API返回搜索亮点需要什么?

我用于构建查询的代码类似于以下内容:

        final HighlightBuilder highlight = new HighlightBuilder()
                .field("*")
                .highlighterType("fvh");

        final SearchRequestBuilder request = client.prepareSearch()
                .setTypes("mytype")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(query)
                .setFrom(currentPage)
                .setSize(perPage)
                .highlighter(highlight)
                .addSort(orderBy.getValue(), sortOrder);

转储查询如下所示:

{
  "from" : 0,
  "size" : 10,
  "query" : {
    "bool" : {
      "must" : [
        {
          "terms" : {
            "my.field" : [
              "myvalue"
            ],
            "boost" : 1.0
          }
        }
      ],
      "disable_coord" : false,
      "adjust_pure_negative" : true,
      "boost" : 1.0
    }
  },
  "sort" : [
    {
      "myotherfield1.myotherfield2.myotherfield3" : {
        "order" : "desc"
      }
    }
  ],
  "highlight" : {
    "type" : "fvh",
    "fields" : {
      "*" : { }
    }
  }
}

我得到了结果,但每次点击的.getHighlightFields()方法返回一张空地图。

1 个答案:

答案 0 :(得分:0)

这似乎有效。需要单独选择字段,而不是使用'_all':

  for(String fieldName : allFields){
      query.should(QueryBuilders.matchPhrasePrefixQuery(fieldName, queryText));
  }
  query.minimumShouldMatch(1);

  final HighlightBuilder highlight = new HighlightBuilder()
          .highlighterType("plain")
          .preTags("")
          .postTags("");

  for(String fieldName : allSearchFields) {
      highlight.field(fieldName);
  }

  final SearchRequestBuilder request = client.prepareSearch()
          .setTypes("mytype")
          .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
          .setQuery(query)
          .setFrom(currentPage)
          .setSize(perPage)
          .highlighter(highlight)
          .addSort(orderBy.getValue(), sortOrder);