博客
关于我
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/

你可能感兴趣的文章
python | pynsist,一个强大的 Python 库!
查看>>
python | pyparsing,一个强大的 Python 库!
查看>>
python | pyqtgraph,一个神奇的 Python 库!
查看>>
python读取文本文件数据
查看>>
python | Python mock对象与测试替身
查看>>
python | Python pandas实现数据追加和合并的最佳方法
查看>>
python | Python 中检查一个数字是否是三态数
查看>>
python | Python 蒙特卡洛模拟
查看>>
python | python-docx,一个超厉害的 Python 库!
查看>>
python | Python中使用@property装饰器
查看>>
python | Python中的functools模块高级应用
查看>>
python | Python中的itertools模块使用技巧
查看>>
python | Python中的事件驱动编程模型
查看>>
python | Python中的内存池与缓存机制
查看>>
python | Python中的弱引用与内存管理
查看>>
python | Python中的类多态:方法重写和动态绑定
查看>>
python | Python作用域链查找机制
查看>>
python | Python俄罗斯方块游戏详解
查看>>
python | Python动态代码执行:exec和compile函数
查看>>
Python读取文件数据进行数据图形化展示
查看>>