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 map = new HashMap();
List listresult = new ArrayList();
 for(final SearchHit hit:response.getHits()){
               final Iterator 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”) + “—”);

“`

你可能感兴趣的:(elasticsearch)