redrubia
redrubia

Reputation: 2366

Accessing Payloads in Elasticsearch Suggestion

I am currently using the Java API for Elasticsearch.

A suggestion query, returns multiple results 'Suggestion', which I want to be able to iterate over and access the variables. This is done by:

val builder = es.prepareSuggest("companies").addSuggestion(new CompletionSuggestionBuilder("companies").field("name_suggest").text(text).size(count()) )   
val suggestResponse = builder.execute().actionGet()
val it = suggestResponse.getSuggest.iterator()

Now

  while (it.hasNext()){
         val info = it.next()
         info.....
  }

I need to be able to access info from the payloads from 'info'. An example of the return looks like:

{
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "companies": [
    {
      "text": "wells",
      "offset": 0,
      "length": 16,
      "options": [
        {
          "text": "Wells Fargo",
          "score": 123.0,
          "payload": {
            "industry_id": 130,
            "id": 776,
            "popularity": 123
          }
        },
        {
          "text": "Wells Real Estate Funds",
          "score": 140.0,
          "payload": {
            "industry_id": 100,
            "id": 778,
            "popularity": 123
          }
        },
        {
          "text": "Wellstar Health System",
          "score": 126.0,
          "payload": {
            "industry_id": 19,
            "id": 1964,
            "popularity": 123
          }
        }
      ]
    }
  ]
}

When iterating through each suggestion, I seem unable to get the payload. Any ideas as to how I can do this?

Upvotes: 4

Views: 2509

Answers (1)

m.stockerl
m.stockerl

Reputation: 91

To access the payloads, you have to iterate over the Option-Objects. (Right now, you are iterating over the suggestions)

import org.elasticsearch.search.suggest.Suggest.Suggestion
import org.elasticsearch.search.suggest.completion.CompletionSuggestion.Entry

...

// Get your "companies" suggestion
val suggestions: Suggestion[Entry] = suggestResponse.getSuggest.getSuggestion("companies")
val it = suggestions.getEntries.iterator()

// Iterate over all entries in the "company" suggestion
while(it.hasNext) {
  val entry = it.next()
  val optionsIt = entry.getOptions.iterator()

  // Iterate over the options of the entry
  while (optionsIt.hasNext) {
    val option = optionsIt.next()

    // As soon as you have the option-object, you can access the payload with various methods
    val payloadAsMap = option.getPayloadAsMap
  }
}

I found the information in the tests of ElasticSearch on Github

Upvotes: 3

Related Questions