1. 程式人生 > >elasticsearch 在查詢的時候如何返回指定的欄位值?

elasticsearch 在查詢的時候如何返回指定的欄位值?

指定返回欄位,查詢方式,

SearchResponse response = client.prepareSearch("sb").setTypes("sb")
                    .setQuery(query).setFrom(0).setSize(500)
                    .setExplain(false)      
                    .addFields(new String[]{"cphm1","jcdid","cplx1","tpid1","tgsj","cdid"})
                    .execute
().actionGet();``` **結果獲取方式:** //指定返回欄位時的結果獲取方式------begin--------- Map<String, Object> map = new HashMap<String, Object>(); List<Map> listresult = new ArrayList<Map>(); for(final SearchHit hit:response.getHits()){ final Iterator<SearchHitField> iterator = hit.iterator
(); while(iterator.hasNext()){ final SearchHitField hitfield = iterator.next(); map.put(hitfield.getName(),hitfield.getValue()); System.out.print(hitfield.getName()+"=="+hitfield.getValue()+"-----"); } listresult.add
(map); System.out.println(); } for(final Map m:listresult){ // System.out.println(m.get("jcdid")+"--"+m.get("cphm1")+"--"+m.get("tpid1")+"--"+m.get("tgsj")); } **普通查詢方式** SearchResponse response = client.prepareSearch("sb").setTypes("sb") .setQuery(query).setFrom(0).setSize(500) .setExplain(false) .execute().actionGet(); 結果獲取方式:

SearchHits hits = response.getHits();
for (int i = 0; i < hits.getHits().length; i++) {
System.out.print(“主鍵值:”+hits.getAt(i).getId()+”—>”);
System.out.print(hits.getAt(i).getSource().get(“cphm1”) + “—”);
System.out.print(hits.getAt(i).getSource().get(“cplx1”) + “—”);
System.out.print(hits.getAt(i).getSource().get(“jcdid”) + “—”);

“`