博客
关于我
java连接elasticsearch:查询、添加数据
阅读量:467 次
发布时间:2019-03-06

本文共 2016 字,大约阅读时间需要 6 分钟。

Elasticsearch Java客户端入门教程:从导入到操作

一、导入必要jar包

在使用Elasticsearch Java客户端进行操作之前,首先需要在项目中添加相应的jar包依赖。以下是具体的配置方式:

org.elasticsearch.client
transport
7.17.0

二、初始化TransportClient对象

通过代码示例了解如何初始化Elasticsearch客户端。以下是一个基本的初始化过程:

private TransportClient initClient() throws UnknownHostException {    String node = esSetting.getClusterNodes();    int index = node.indexOf(":");    String host = node.substring(0, index);    int port = Integer.valueOf(node.substring(index + 1));    Settings settings = Settings.builder()            .put("cluster.name", esSetting.getClusterName())            .put("client.transport.sniff", true)            .build();    InetAddress address = InetAddress.getByName(host);    TransportClient client = new PreBuiltTransportClient(settings);    client.addTransportAddress(new InetSocketTransportAddress(address, port));    return client;}

三、基本操作:查询数据

通过以下代码示例可以对Elasticsearch索引进行查询操作:

// 构建查询条件QueryBuilder queryBuilder = QueryBuilders.boolQuery()        .must(QueryBuilders.rangeQuery("date")                .gte("2018-11-08T00:00:00.000Z")                .lt("2018-11-09T00:00:00.000Z"));// 配置搜索参数String index = "index";String type = "type";SearchResponse response = client.prepareSearch(index)        .setTypes(type)        .addSort("date", SortOrder.ASC)        .setSize(1000)        .setQuery(queryBuilder)        .execute()        .actionGet();// 处理结果long total = response.getHits().getTotalHits();

四、基本操作:写入数据

以下代码示例展示了如何向Elasticsearch索引中写入新数据:

try {    XContentBuilder builder = XContentFactory.jsonBuilder()            .startObject()            .field("date", "2018-11-08T00:00:00.000Z")            .field("cost", 10)            .endObject();    IndexResponse response = client            .prepareIndex(index, type)            .setSource(builder)            .get();} catch (Exception e) {    e.printStackTrace();}

以上代码示例涵盖了从导入依赖到客户端初始化、查询操作以及数据写入的完整流程。如果需要更详细的功能说明或其他操作,请参考Elasticsearch官方文档或相关技术博客。

转载地址:http://fkdbz.baihongyu.com/

你可能感兴趣的文章
POJ 2362 Square DFS
查看>>
Qt笔记——解决添加Qt Designer Form Class时“allocation of incomplete type Ui::”
查看>>
poj 2386 Lake Counting(BFS解法)
查看>>
poj 2387 最短路模板题
查看>>
POJ 2391 多源多汇拆点最大流 +flody+二分答案
查看>>
POJ 2403
查看>>
poj 2406 还是KMP的简单应用
查看>>
POJ 2431 Expedition 优先队列
查看>>
Qt笔记——获取位置信息的相关函数
查看>>
POJ 2484 A Funny Game(神题!)
查看>>
POJ 2486 树形dp
查看>>
POJ 2488:A Knight's Journey
查看>>
SpringBoot为什么易学难精?
查看>>
poj 2545 Hamming Problem
查看>>
poj 2723
查看>>
poj 2763 Housewife Wind
查看>>
Qt笔记——模型/视图MVD 文件目录浏览器软件
查看>>
POJ 2892 Tunnel Warfare(树状数组+二分)
查看>>
poj 2965 The Pilots Brothers' refrigerator-1
查看>>
poj 3026( Borg Maze BFS + Prim)
查看>>