博客
关于我
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 GPS 模块:读取最新的 GPS 数据
查看>>
python grpc入门
查看>>
python gRPC测试helloworld
查看>>
python list,str的拼接与转换
查看>>
python matplotlib简单使用
查看>>
python nltk nltk_data 离线安装,chatterbot
查看>>
python os.system
查看>>
Python os.system执行多条语句,os.system的返回值以及与os.popen的区别
查看>>
Python os和sys模块
查看>>
python os文件/目录
查看>>
Python Package 之 Faker(随机姓名、电话)
查看>>
Python Panda TIME 系列重新采样
查看>>
python pandas TimeStamps到夏令时的本地时间字符串
查看>>
Python pandas 数据清洗与数据绘图实战
查看>>
Python Pandas 用顶行替换标题
查看>>
Python pandas 通过 dt 访问器有效地将日期时间转换为时间戳
查看>>
Python Pandas-从DataFrame按类别绘制多个条形图
查看>>
Python Pandas:每月或每周拆分 TimeSerie
查看>>
python pandas中融化的对面
查看>>
python pandas从时间序列中提取唯一日期
查看>>