2017-04-22 85 views
0

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

ElasticSearch V5.3.1

弹性API:org.elasticsearch.client:运输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总是回来空。 Fields有一个关键字title.raw的项目,它有一个SearchHitField。

回答

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" 
    ] 
    } 
} 
+0

我明白了。所以你说的是,我的领域都没有被标记为存储,这就是为什么他们不可用。但是我可以从源访问数据。 – Seamus

+0

遵循你的建议,我使用了源代码: 'Map source = hit.getSource();' 这让我可以访问所有的字段。谢谢! – Seamus