简体   繁体   中英

Java Elastic Search: Highlighter not working

I'm using the Java API for ElasticSearch. I'm attempting to highlight my fields but it's not working. The correct results that match the search term are being returned, so there is content to highlight, but it simply won't do it. I set my SearchResponse and HighlightBuilder like this:

    QueryBuilder matchQuery = simpleQueryStringQuery(searchTerm);
    ...
    HighlightBuilder highlightBuilder = new HighlightBuilder()
            .postTags("<highlight>")
            .preTags("</highlight>")
            .field("description");

    SearchResponse response = client.prepareSearch("mediaitems")
            .setTypes("mediaitem")
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(matchQuery)                 // Query
            .setFrom(from)
            .setSize(pageSize)
            .setExplain(true)
            .highlighter(highlightBuilder)
            .get();

and in my JSON->POJO code, I check to see which fields have been highlighted, but the returned Map is empty.

    Arrays.stream(hits).forEach((SearchHit hit) -> {
        String source = hit.getSourceAsString();
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        try {
            MediaItem mediaItem = objectMapper.readValue(source, MediaItem.class);
            mediaItemList.add(mediaItem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

Why on earth is my highlighting request being ignored?

Any help is greatly appreciated.

You have to set the highlighted field in HighlightBuilder.

For example:

HighlightBuilder.Field field = new HighlightBuilder.Field(fieldName);
highlightBuilder.field(field);

I saw you are using simple query string query, so you can do the following:

Your query string: fieldname: searched text

So for example your query string is the following:

price: >2000 && city: Manchaster

With this query string you specified the fields in the query too. Now highlighter should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM