ES如何指定返回的字段field

2021-08-22 11:29:32 字數 2415 閱讀 7021

在elasticsearch 2.x版本中,如果我們想指定查詢返回的字段,可以使用fields欄位設定,**如下:

string index = ***;

string type = ***;

// 指定要返回的字段

string fields = new string[2];

fields[0] = "field1"; // 欄位1名稱

fields[1] = "filed2"; // 欄位2名稱

// 構造query

searchrequestbuilder requestbuilder = client.preparesearch(index);

requestbuilder .setfrom(0).setsize(100)

.settimeout(timevalue.timevaluemillis(300))

.settypes(type)

.addfields(fields);

// bool 條件

boolquerybuilder boolquerybuilder = querybuilders.boolquery();

termquerybuilder tqb = querybuilders.termquery("field1", "val1");

boolquerybuilder.must(tqb);

// set query

requestbuilder.setquery(boolquerybuilder);

// get response

searchresponse response = requestbuilder.execute().actionget();

// 遍歷返回的字段

searchhits searchhits = response.gethits();

for (searchhit hit : searchhits)

但是在5.x中,setfileds函式已經不存在了,那在5.x中通過什麼來指定返回的字段呢,答案是source欄位,通過setfetchsource函式來指定要返回的字段,可以指定單個filed或者乙個filed陣列,通過getsource來獲取返回的字段值,其中setfetchsource有三個版本,說明如下: 

1. setfetchsource(boolean fetch) 

用於指定是否返回字段,預設為true,如果為false,則getsource返回null。 

2. setfetchsource(string include, string exclude) 

用於指定包含的乙個欄位和排除的乙個字段,實際會返回include欄位及其對應的值。 

3. setfetchsource(string includes, string excludes) 

用於指定包含的多個欄位和排除的多個字段。 

下面以具體**來說明如何獲取:

string index = ***;

string type = ***;

// 指定要返回的字段

string fields = new string[2];

fields[0] = "field1"; // 欄位1名稱

fields[1] = "filed2"; // 欄位2名稱

// 構造query

searchrequestbuilder requestbuilder = client.preparesearch(index);

requestbuilder .setfrom(0).setsize(100)

.settimeout(timevalue.timevaluemillis(300))

.settypes(type)

// 指定返回的字段,排除欄位設為null

.setfetchsource(fields, null);

// bool 條件

boolquerybuilder boolquerybuilder = querybuilders.boolquery();

termquerybuilder tqb = querybuilders.termquery("field1", "val1");

boolquerybuilder.must(tqb);

// set query

requestbuilder.setquery(boolquerybuilder);

// get response

searchresponse response = requestbuilder.execute().actionget();

// 遍歷返回的字段

searchhits searchhits = response.gethits();

for (searchhit hit : searchhits)

ES如何指定返回的字段field

在elasticsearch 2.x版本中,如果我們想指定查詢返回的字段,可以使用fields欄位設定,如下 string index string type 指定要返回的字段 string fields new string 2 fields 0 field1 欄位1名稱 fields 1 fil...

es 指定排序字段 ES 系列2 資料寫入分析

當出現文件寫入請求時,es 內部到底發生了哪些過程?面對大批量的寫入請求,es 如何可以做到近實時的可搜尋?為了滿足聚合分析的等功能,es 又做了哪些事情?本文試圖對這些問題進行回答,文章大綱如下所示 文件寫入操作 es 內部文件處理過程 文件最終資料格式 建立索引 put twitter 插入文件...

通過id查詢使用者,但是只返回指定的字段

使用hibernate和spring mvc 通過id查詢到乙個使用者,但是只返回指定的字段 方式一 拼接hql 通過資料庫id查詢使用者,但是只返回指定的字段 param id param propertynames 指定的多個成員變數 return public object getproper...