elasticsearch 查询 - 过滤数据列
过滤数据列指的是只查询需要的列 例如 title,content,price等
方式1 restful api
POST http://192.168.199.126:9200/film/dongzuo/_search/
{
"from": 0,
"size": 2,
"_source": {
"include": [
"title",
"price"
]
}
}

方式2 Java接口实现
private TransportClient client;
private static String host="192.168.199.126";
private static int port=9300; // 程序连接的端口
// 配置settings 集群相关
private static Settings.Builder settings = Settings.builder().put("cluster.name","my-application");
@Before
public void init() throws UnknownHostException {
client = new PreBuiltTransportClient(settings.build())
.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
}
@After
public void close(){
if(client!=null){
client.close();
}
}
/**
* 数据列过滤
* @throws Exception
*/
@Test
public void searchInclude()throws Exception{
// 设置要查询的索引名称和类型 多个之间使用逗号隔开
SearchRequestBuilder srb=client.prepareSearch("film").setTypes("dongzuo");
SearchResponse sr=srb.setQuery(QueryBuilders.matchAllQuery())
// 参数1 指定要查询的列 参数2 不包含的列
.setFetchSource(new String[]{"title","price"}, null)
.execute()
.actionGet(); // 分页排序所有
SearchHits hits=sr.getHits();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
