在Elasticsearch建议中访问有效负载

时间:2014-02-10 21:03:24

标签: elasticsearch search-suggestion

我目前正在使用Java API for Elasticsearch。

建议查询,返回多个结果'Suggestion',我希望能够迭代并访问变量。这可以通过以下方式完成:

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()

现在

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

我需要能够从'info'访问来自有效负载的信息。返回的示例如下:

{
  "_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
          }
        }
      ]
    }
  ]
}

在遍历每个建议时,我似乎无法获得有效负载。关于我如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:3)

要访问有效负载,您必须遍历Option-Objects。 (现在,你正在迭代建议)

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
  }
}

我在ElasticSearch on Github

的测试中找到了这些信息