/**
* 可以设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,
* 把集群中其它机器的ip地址加到客户端中,这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端,
* 它会自动帮你添加,并且自动发现新加入集群的机器。
*/
Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff", true).build();
TransportClient client = new TransportClient(settings);
实例应用:
使用TransportClient初始化客户端并执行简单搜索:
package com.bbf.client;
import Java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import com.bbf.search.model.Datum;
/**
* description:
*
* @author <a href='https://www.linuxidc.com/mailto:dennisit@163.com'> Cn.pudp (En.dennisit)</a> Copy Right since 2013-9-29
*
* com.bbf.client.ESClient.java
*
*/
public class ESClient {
/**在运行该测试实例时,已经在本地建立了对应的索引库datum*/
public static void main(String[] args) {
//自定义集群结点名称
String clusterName = "elasticsearch_pudongping";
//程序中更改集群结点名称 并且设置client.transport.sniff为true来使客户端去嗅探整个集群的状态
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", clusterName).put("client.transport.sniff", true).build();
//创建客户端对象
TransportClient client = new TransportClient(settings);
//客户端对象初始化集群内结点,绑定多个ip
//client.addTransportAddress(new InetSocketTransportAddress("192.168.0.149", 9300));
client.addTransportAddress(new InetSocketTransportAddress("192.168.0.162", 9300));
//搜索,根据Id查询
GetResponse response = client.prepareGet("datum", "datum", ""+130)
.execute()
.actionGet();
//查询结果映射成对象类
ObjectMapper mapper = new ObjectMapper();
Datum datum= mapper.convertValue(response.getSource(), Datum.class);
System.out.println("资讯编号:" + datum.getId() +"\t资讯标题:"+datum.getTitle() );
//构造查询器查询,第一个参数为要查询的关键字,第二个参数为要检索的索引库中的对应索引类型的域
QueryBuilder query = QueryBuilders.multiMatchQuery("恩必普", "keyword");
//第一个参数datum表示索引库,第二个参数datum表示索引类型,from表示开始的位置 size表示查询的条数 ,类似mysql中的limit3,5
SearchResponse searchResponse = client.prepareSearch("datum").setTypes("datum").setQuery(query).setFrom(3).setSize(5).execute().actionGet();
//将搜索结果转换为list集合对象
List<Datum> lists = getBeans(searchResponse);
System.out.println("查询出来的结果数:" + lists.size());
for(Datum dtm: lists){
System.out.println("资讯编号:" + dtm.getId() +"\t资讯标题:"+dtm.getTitle());
}
//关闭客户端
client.close();