4

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?

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
redrubia
  • 2,256
  • 6
  • 33
  • 47

1 Answers1

3

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

m.stockerl
  • 91
  • 2
  • 1
    Thanks for your helpful answer. Just as a hint for other Java developers: I have to cast `Suggest.Suggestion.Entry.Option` to `CompletionSuggestion.Entry.Option` just like in the linked tests. – Sonson123 May 21 '15 at 12:29