Java API操作ElasticSearch

1.什么是JavaAPI

ES对Java提供一套操作索引库的工具包,即Java API。所有的ES操作都使用Client对象执行。
ES的Maven引入

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>

2.连接ES获取Client对象

2.1、 把每台服务的ip 端口配上

TransportClient 利用transport模块远程连接一个ES集群。它并不加入到集群中,只是简单的获得一个或者多个初始化的transport地址,并以轮询的方式与这些地址进行通信。

// on startup
TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));
// on shutdown
client.close();

2.2、通过集群名称来查找

注意,如果你有一个与 ES集群不同的集群,你可以设置机器的名字。

Settings settings = Settings.builder()
    .put("cluster.name", "myClusterName").build();
TransportClient client = new PreBuiltTransportClient(settings);
//添加地址到client中

2.3、推荐使用方式

你可以设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中,这样做的好处是一般你不用手动设置集群里所有集群的ip到连接客户端,它会自动帮你添加,并且自动发现新加入集群的机器。代码实例如下:

Settings settings = Settings.builder()
	.put("client.transport.sniff", true).build();
TransportClient client = new PreBuiltTransportClient(settings)
	.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300))

3.索引API

3.1、创建文档索引

ES索引文档非常方便,只需要构建好需要索引的JSON格式数据,然后调用API:

//新增
@Test
public void testES() throws Exception{
    //得到client
    TransportClient client = getClient();
    IndexRequestBuilder builder = client.prepareIndex("aisell", "user", "1");
    Map mp = new HashMap();
    mp.put("name","张三");
    mp.put("age",28);
    builder.setSource(mp);
    IndexResponse indexResponse = builder.get();
    System.out.println(indexResponse);
    client.close();
}

3.2、获取文档

//查询 --springdata es
@Test
public void testGet() throws Exception{
    //得到client
    TransportClient client = getClient();
    System.out.println(client.prepareGet("aisell", "user", "1").get().getSource());
    client.close();
}

3.3、更新文档

//修改
@Test
public void testUpdate() throws Exception{
    TransportClient client = getClient();
    IndexRequest indexRequest = new IndexRequest("aisell", "user", "1");
    Map mp = new HashMap();
    mp.put("name","李四");
    mp.put("age",34);
    //不存在 就新增 存在 就更新
    UpdateRequest updateRequest = new UpdateRequest("aisell", "user", "1").doc(mp).upsert(indexRequest);
    //执行
    client.update(updateRequest).get();
    client.close();
}

3.4、删除文档

//删除
@Test
public void testDel() throws Exception{
    TransportClient client = getClient();
    client.prepareDelete("aisell","user","1").get();
    client.close();
}

3.5、批量操作

//批量操作
@Test
public void testBulk() throws Exception{
    TransportClient client = getClient();
    BulkRequestBuilder req = client.prepareBulk();
    for(int i=0;i<50;i++){
        Map mp = new HashMap();
        mp.put("name","李四"+i);
        mp.put("age",0+i);
        req.add(client.prepareIndex("shoppings","goods",""+i).setSource(mp));
    }
    BulkResponse responses = req.get();
    if(responses.hasFailures()){
        System.out.println("出问题了。。。。。");
    }
}

3.6、搜索

ES的查询是通过执行json格式的查询条件,在java中就是构造QueryBuilder对象,ES完全支持queryDSL风格的查询方式,QueryBuilder的构建类是QueryBuilders,filter的构建类是FilterBuilders。

@Test
public void testDSL() throws Exception{
   //得到client对象
   TransportClient client = getClient();
   //得到builder
   SearchRequestBuilder builder = client.prepareSearch("shoppings").setTypes("goods");
   //得到bool对象
   BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
   //得到must
   List<QueryBuilder> must = boolQuery.must();
   must.add(QueryBuilders.matchAllQuery());
   //添加filter过滤器
   boolQuery.filter(QueryBuilders.rangeQuery("age").gte("18").lte("34"));
   builder.setQuery(boolQuery);
   //添加分页
   builder.setFrom(0);
   builder.setSize(10);
   //设置排序
   builder.addSort("age", SortOrder.DESC);
   //设置查询字段
   builder.setFetchSource(new String[]{"name","age"},null);
   //取值
   SearchResponse response = builder.get();
   //得到查询内容
   SearchHits hits =  response.getHits();
   //得到命中数据 返回数组
   SearchHit[] hitsHits = hits.getHits();
   //循环数组 打印获取值
   for (SearchHit hitsHit : hitsHits) {
       System.out.println("得到结果"+hitsHit.getSource());
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值