ElasticSearch命中没有字段

时间:2017-04-22 19:49:08

标签: java elasticsearch

我遇到了一个问题,当我使用java api运行弹性搜索时,我得到了结果...但是当我尝试从结果中提取值时,没有字段。

ElasticSearch v5.3.1

Elastic API:org.elasticsearch.client:transport v5.3.0

我的代码:

SearchRequestBuilder srb =   client.prepareSearch("documents").setTypes("documents").setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(qb).setFrom(0).setSize((10)).setExplain(false);

srb.addDocValueField("title.raw");
SearchResponse response = srb.get();

response.getHits().forEach(new Consumer<SearchHit>() {

        @Override
        public void accept(SearchHit hit) {
            System.out.println(hit);
            Map<String, SearchHitField> fields = hit.getFields();

            Object obj = fields.get("title.raw").getValue();

        }

    });

当forEach运行时,obj总是返回null。 Fields中有一个带有title.raw键的项目,它有一个SearchHitField。

1 个答案:

答案 0 :(得分:1)

字段仅在您尝试获取存储的字段时使用。默认情况下,您应该使用源获取字段。使用以下代码示例,我将尝试解释它。

PUT documents
{
  "settings": {
    "number_of_replicas": 0,
    "number_of_shards": 1
  },
  "mappings": {
    "document": {
      "properties": {
        "title": {
          "type": "text",
          "store": true
        },
        "description": {
          "type": "text"
        }
      }
    }
  }
}

PUT documents/document/_bulk
{"index": {}}
{"title": "help me", "description": "description of help me"}
{"index": {}}
{"title": "help me two", "description": "another description of help me"}

GET documents/_search
{
  "query": {
    "match": {
      "title": "help"
    }
  },
  "stored_fields": ["title"],
  "_source": {
    "includes": ["description"]
  }
}

接下来的回复,注意存储的字段标题和正常字段描述之间的差异。

{
  "_index": "documents",
  "_type": "document",
  "_id": "AVuciB12YLj8D0X3N5We",
  "_score": 0.14638957,
  "_source": {
    "description": "another description of help me"
  },
  "fields": {
    "title": [
      "help me two"
    ]
  }
}