2017-04-22 26 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