Search code examples
elasticsearchspring-dataelastic-stackspring-data-elasticsearch

Spring Data Elastic Search @Query @Highlight


I can't get the highlighted fields with this query code, any thought on it, I'm using SDE4.0.0.RC2, i want to use @Query:

@Query("{\n" +
           "  \"multi_match\": {\n" +
           "    \"query\": \"?0\",\n" +
           "    \"fields\": [\n" +
           "      \"code^2\",\n" +
           "      \"name\"\n" +
           "    ],\n" +
           "    \"analyzer\": \"standard\"\n" +
           "  }\n" +
           "}")
   @Highlight(
           fields = @HighlightField(
                   name = "['code','name']"),
           parameters = @HighlightParameters(
                   preTags = "<strong>",
                   postTags = "</strong>",
                   fragmentSize = 500,
                   numberOfFragments = 3
           )
   )
   List<CodeNames> findAllByCodeAndNameOrderByName(String code, Pageable pageable);

Solution

  • You need the specify each highlight field in a separate annotation argument:

       @Query("{\n" +
                "  \"multi_match\": {\n" +
                "    \"query\": \"?0\",\n" +
                "    \"fields\": [\n" +
                "      \"code^2\",\n" +
                "      \"name\"\n" +
                "    ],\n" +
                "    \"analyzer\": \"standard\"\n" +
                "  }\n" +
                "}")
        @Highlight(
            fields = {
                @HighlightField(name = "code"),
                @HighlightField(name = "name")
            },
            parameters = @HighlightParameters(
                preTags = "<strong>",
                postTags = "</strong>",
                fragmentSize = 500,
                numberOfFragments = 3
            )
        )
        List<CodeNames> findAllByCodeAndNameOrderByName(String code, Pageable pageable);
    

    Edit:

    In addition to that you have to change the return type of your method:

    List<SearchHit<CodeNames>> findAllByCodeAndNameOrderByName(String code, Pageable pageable);
    

    or

    SearchHits<CodeNames> findAllByCodeAndNameOrderByName(String code, Pageable pageable);
    

    to be able to read the highlight values from the returned SearchHit, see https://docs.spring.io/spring-data/elasticsearch/docs/4.0.0.RC2/reference/html/#elasticsearch.operations.searchresulttypes