博客
关于我
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 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
查看>>
Python 字符串的几种拼装方式
查看>>
python 存入数据库bigint_python基础_MySQL的bigint类型
查看>>
python 学习 面向对象编程
查看>>
Python 学习日记第三篇 -- 字典
查看>>
Python 学习笔记(一)Data type
查看>>
python 安装echarts
查看>>
python 安装opencv及问题解决
查看>>
Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
查看>>
Python 安装避坑指南:从入门到进阶
查看>>
Python 安装配置详解
查看>>
python 实现儿童算术游戏
查看>>
python 实现字符串转整型
查看>>
Python 实现定时任务的八种方案!
查看>>
Python 实现自动化测试 dubbo 协议接口
查看>>
python 对json数据读取及保存与读取,对dump,dumps,load,loads的理解
查看>>
Python 对mysql数据库的操作
查看>>
Python 对象数据库列表
查看>>
Python 导入requests报错No module named requests
查看>>
python 将函数加到列表中进行调用
查看>>