java连接elasticsearch:查询、添加数据
2024-08-28 06:03:35
导入jar包
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/transport -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
</dependency>
初始化TransportClient对象
/**
* 初始化TransportClient对象, 这里只配置了单个节点,例如100.100.0.1:8090
*/
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()
//elasticsearch节点名称
.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;
}
查询:
//查询,根据数据中date字段查询, 这里是最常用的boolQuery示例,可以通过must、must_not、filter等方法设定查询条件
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.rangeQuery("date").gte("2018-11-08T00:00:00.000Z")
.lt("2018-11-09T00:00:00.000Z")); //elasticsearch索引及类型,对应数据库中数据库和表
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();
写入:
try {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject().field("date", "2018-11-08T00:00:00.000Z")
.field("cost", 10);
builder.endObject();
IndexResponse response = client
.prepareIndex(index, type)
.setSource(builder).get();
} catch (Exception e) {
e.printStackTrace();
}
最新文章
- inference和learning
- Afinal
- 安装SQL Server 2005
- [HDU 3689]Infinite monkey theorem (KMP+概率DP)
- PCL—低层次视觉—点云分割(最小割算法)
- 超轻量级spring模板方案
- 判断IE浏览器用IE条件表达式
- CouchBase 遇到问题笔记(一)
- Xah Lee Web 李杀网
- Error: ORA-16501: the Data Guard broker operation failed ORA-16625: cannot reach database
- STM32驱动TEA5767收音机模块
- 安装win8+Ubuntu14.04双系统的经验总结
- 注入理解之APC注入
- CF1033G Chip Game
- ES6 中 Promise
- pytorch kaggle 泰坦尼克生存预测
- shell启动执行cypher语句
- CSS 表格实例
- HDU1548- A strange lift (BFS入门)
- Javascript中的this之我见
热门文章
- spring data jpa 原生sql 别名字段无法注入
- vue element 中自定义传值
- Project Euler Problem 24-Lexicographic permutations
- 洛谷 1372 又是毕业季I
- Java Annotation详解(二): 反射和Annotation
- 2006年NOIP普及组复赛题解
- jQuery中动态创建、添加元素的方法总结
- 2018-8-10-win10-uwp-使用-Geometry-resources-在-xaml
- java方法里的属性
- Codeforces Round #200 (Div. 1 + Div. 2)