Home > Blockchain >  How to "Explicitly order highlighted fields" using ElasticSearch Java API client v7.16?
How to "Explicitly order highlighted fields" using ElasticSearch Java API client v7.16?

Time:03-05

I want to explicitly order highlighted fields using the Elasticsearch Java API Client 7.16.

In other words I want to build the following request

GET /_search
{
  "highlight": {
    "fields": [
      { "a": {} },
      { "b": {} },
      { "c": {} }
    ]
  }
}

Unfortunately the following code ignores the insertion order:

        new Highlight.Builder()
            .fields("a", new HighlightField.Builder().build())
            .fields("b", new HighlightField.Builder().build())
            .fields("c", new HighlightField.Builder().build());

Actually all available fields() methods eventually put the data in the unordered map. So my request actually is following:

GET /_search
{
  "highlight": {
    "fields": {
      "b": {},
      "c": {},
      "a": {}
    }
  }
}

Is there any other Java API that allows to control the order of highlighted fields?

CodePudding user response:

As i know this is not possible and this is not issue of elasticsearch but it is how JSON work. Below is mentioned in JSON documentation.

An object is an unordered set of name/value pairs

I am not sure why you want to rely on order. You should not rely on the ordering of elements within a JSON object.

You can pass Map of field like below for order, just check javadoc:

    Map<String, HighlightField> test = new HashMap();
    test.put("a", new HighlightField.Builder().build());
    test.put("b", new HighlightField.Builder().build());
    test.put("b", new HighlightField.Builder().build());
    
    Builder highlight = new Highlight.Builder().fields(test);

CodePudding user response:

Can you please tell what all dependencies you have regarding Elasticsearch?

Because there is class HighlightBuilder present in package

package org.elasticsearch.search.fetch.subphase.highlight;

Which has following property as member variable,

private boolean useExplicitFieldOrder = false;

The you can build

 List<HighlightBuilder.Field> fields1 = new ArrayList<>();
            fields1.add(new HighlightBuilder.Field("a"));
            fields1.add(new HighlightBuilder.Field("b"));
            fields1.add(new HighlightBuilder.Field("c"));
    
HighlightBuilder highlightBuilder = new HighlightBuilder(null,null,fields1).useExplicitFieldOrder(true);
  • Related