es使用java的api操作
基本环境的创建
pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.player3.es</groupId>
<artifactId>estest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>estest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch的客户端 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
<!-- elasticsearch依赖2.x的log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.player3.es.estest.EstestApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
创建索引 EsTest_Client
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
///关闭连接
esclient.close();
}
通过:localhost:9200/_cat/indices?v 查看,确实新增一条索引
查询索引 EsTest_index_search
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
GetIndexRequest player3 = new GetIndexRequest("player3");
GetIndexResponse response = esclient.indices().get(player3, RequestOptions.DEFAULT);
System.out.println(response.getAliases());
System.out.println(response.getDataStreams());
System.out.println(response.getDefaultSettings());
System.out.println(response.getIndices());
System.out.println(response.getMappings());
System.out.println(response.getSettings());
///关闭连接
esclient.close();
}
删除索引: EsTest_index_delete
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
DeleteIndexRequest shoppingg = new DeleteIndexRequest("shoppingg");
AcknowledgedResponse delete = esclient.indices().delete(shoppingg, RequestOptions.DEFAULT);//create(request, RequestOptions.DEFAULT);
///关闭连接
System.out.println(delete.isAcknowledged());
esclient.close();
}
在索引下新增数据 EsTest_Client_Doc_Insert
class User
private String name;
private String sex;
private Integer age;
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//插入数据
IndexRequest indexRequest = new IndexRequest();
//需要插入的数据 index|索引 id|唯一标识
indexRequest.index("user").id("1020");
User user = new User();
user.setName("李为");
user.setSex("男");
user.setAge(27);
// 向es插入数据,必须将数据转换为json jackson
ObjectMapper mapper=new ObjectMapper();
String userjson = mapper.writeValueAsString(user);//对象转str
indexRequest.source(userjson, XContentType.JSON);//index为user,id1020的数据
IndexResponse index = esclient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index);
///关闭连接
esclient.close();
}
索引下的修改数据 EsTest_Client_Doc_Update
//TODO 如果直接把全部的值替换 就是全量更新
// public static void main(String[] args) throws IOException {
// //创建es客户端对象
// RestHighLevelClient esclient = new RestHighLevelClient(
// RestClient.builder(new HttpHost("localhost",9200,"http"))
// );
// //插入数据
// IndexRequest indexRequest = new IndexRequest();
// //需要插入的数据 index|索引 id|唯一标识
// indexRequest.index("user").id("1020");
//
// User user = new User();
// user.setName("李为");
// user.setSex("男");
// user.setAge(26);
// // 向es插入数据,必须将数据转换为json jackson
// ObjectMapper mapper=new ObjectMapper();
// String userjson = mapper.writeValueAsString(user);//对象转str
// indexRequest.source(userjson, XContentType.JSON);//index为user,id1020的数据
// IndexResponse index = esclient.index(indexRequest, RequestOptions.DEFAULT);
// System.out.println(index);
// ///关闭连接
// esclient.close();
// }
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
UpdateRequest update = new UpdateRequest();
update.index("user").id("1020");
update.doc(XContentType.JSON,"sex","女","age",18);
esclient.update(update, RequestOptions.DEFAULT);
esclient.close();
}
索引下的删除数据 EsTest_Client_Doc_delete
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index("user").id("1020");
esclient.delete(deleteRequest, RequestOptions.DEFAULT);
///关闭连接
esclient.close();
}
索引下的批量插入 EsTest_Client_Doc_insert_bash
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1010").source(XContentType.JSON,
"name","李伟","age",27,"sex","男"));
request.add(new IndexRequest().index("user").id("1011").source(XContentType.JSON,
"name","lisi","age",22,"sex","女"));
request.add(new IndexRequest().index("user").id("1012").source(XContentType.JSON,
"name","wangwu","age",26,"sex","女"));
request.add(new IndexRequest().index("user").id("1013").source(XContentType.JSON,
"name","zhaoliu","age",27,"sex","女"));
esclient.bulk(request, RequestOptions.DEFAULT);
///关闭连接
esclient.close();
}
索引下的批量删除数据 EsTest_Client_Doc_delete_bash
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1010"));
request.add(new DeleteRequest().index("user").id("1011"));
request.add(new DeleteRequest().index("user").id("1012"));
request.add(new DeleteRequest().index("user").id("1013"));
esclient.bulk(request, RequestOptions.DEFAULT);
///关闭连接
esclient.close();
}
条件查询之全部查询 EsTest_Client_Query
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
//查询所有的数据
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
// System.out.println(search);
SearchHits hits = search.getHits();
System.out.println(hits.getTotalHits());
System.out.println(search.getTook());
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
///关闭连接
esclient.close();
}
条件查询之匹配查询 EsTest_Client_termQuery
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest req = new SearchRequest();
req.indices("user");
req.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",27))); SearchResponse search = esclient.search(req, RequestOptions.DEFAULT); ///关闭连接
esclient.close();
SearchHits hits = search.getHits();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
}
条件查询之分页查询 EsTest_Client_From_Size
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
query.from(0);//当前页
query.size(3);//每页条数
searchRequest.indices("user");
searchRequest.source(query);
// searchRequest.
SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
///关闭连接
esclient.close();
}
条件查询之排序 EsTest_Client_From_Size_Sort
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
query.from(0);//当前页
query.size(3);//每页条数
query.sort("age", SortOrder.DESC);
searchRequest.indices("user");
searchRequest.source(query);
// searchRequest.
SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
///关闭连接
esclient.close();
}
条件查询之排除某列 EsTest_Client_Fetch
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
String[] includes={};//包含
String[] excludes={"age"};//排除 query.fetchSource(includes,excludes);
searchRequest.indices("user");
searchRequest.source(query);
// searchRequest.
SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = search.getHits();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
}
///关闭连接
esclient.close();
}
组合查询 EsTest_Client_Should
查询男人 年龄30的
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder bool = new BoolQueryBuilder();
bool.must(QueryBuilders.matchQuery("sex","男"));
bool.must(QueryBuilders.matchQuery("age",27));
//组合查询
builder.query(bool);
searchRequest.source(builder); SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
///关闭连接
SearchHits hits = search.getHits();
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
查询不是男人的
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder bool = new BoolQueryBuilder();
bool.must(QueryBuilders.matchQuery("age",27));
bool.mustNot(QueryBuilders.matchQuery("sex","男"));
//组合查询
builder.query(bool);
searchRequest.source(builder); SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
///关闭连接
SearchHits hits = search.getHits();
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
年龄为26或27
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder bool = new BoolQueryBuilder();
// age=27 and sex =男
// bool.must(QueryBuilders.matchQuery("age",27));
// bool.mustNot(QueryBuilders.matchQuery("sex","男")); //age=26 or age=27
bool.should(QueryBuilders.matchQuery("age",27));
bool.should(QueryBuilders.matchQuery("age",26)); //组合查询
builder.query(bool);
searchRequest.source(builder); SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
///关闭连接
SearchHits hits = search.getHits();
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
年龄大于等于27小于40
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
//年龄大于等于27小于40
RangeQueryBuilder age = QueryBuilders.rangeQuery("age");
age.gte(27);
age.lt(40);
//组合查询
builder.query(age);
searchRequest.source(builder); SearchResponse search = esclient.search(searchRequest, RequestOptions.DEFAULT);
///关闭连接
SearchHits hits = search.getHits();
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
高亮查询 EsTest_Client_GaoLiang
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhaoliu"); //SearchSourceBuilder 带有高亮标签
//记住这里是创建的不是 builder.highlighter 空参弄出来的,不然会报错的
HighlightBuilder highlighter = new HighlightBuilder();
highlighter.preTags("<font color='red'>");//前缀
highlighter.postTags("</font>");//后缀
highlighter.field("name");//name属性高亮显示
builder.highlighter(highlighter);
builder.query(termQueryBuilder); request.source(builder);
SearchResponse search = esclient.search(request, RequestOptions.DEFAULT); SearchHits hits = search.getHits();
///关闭连接
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
聚合查询
求最大值
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
MaxAggregationBuilder field = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(field);
request.source(builder);
SearchResponse search = esclient.search(request, RequestOptions.DEFAULT); SearchHits hits = search.getHits();
///关闭连接
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
分组
public static void main(String[] args) throws IOException {
//创建es客户端对象
RestHighLevelClient esclient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermsAggregationBuilder ageGroup = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(ageGroup);
request.source(builder);
SearchResponse search = esclient.search(request, RequestOptions.DEFAULT); SearchHits hits = search.getHits();
///关闭连接
esclient.close();
for(SearchHit hit:hits){
System.out.println(hit.getSourceAsString());
} }
es使用java的api操作的更多相关文章
- ES的java端API操作
首先简单介绍下写这篇博文的背景,最近负责的一个聚合型的新项目要大量使用ES的检索功能,之前对es的了解还只是纯理论最多加个基于postman的索引创建操作,所以这次我得了解在java端如何编码实现:网 ...
- ES系列十五、ES常用Java Client API
一.简介 1.先看ES的架构图 二.ES支持的客户端连接方式 1.REST API http请求,例如,浏览器请求get方法:利用Postman等工具发起REST请求:java 发起httpClien ...
- Java原生API操作XML
使用Java操作XML的开源框架比较多,如著名的Dom4J.JDOM等,但个人认为不管你用那个框架都要对JDK原生的API有所了解才能更得心应手的应用.本篇就来简单了解下原生的XML API. JAV ...
- 读《分布式一致性原理》JAVA客户端API操作3
更新数据 客户端可以通过zookeeper的API来更新一个节点的数据内容,有如下两个接口: public Stat setData(final String path, byte data[], i ...
- 读《分布式一致性原理》JAVA客户端API操作2
创建节点 通过客户端API来创建一个数据节点,有一下两个接口: public String create(final String path, byte data[], List<ACL> ...
- 读《分布式一致性原理》JAVA客户端API操作
创建会话 客户端可以通过创建一个Zookeeper实例来连接服务器.4种构造方法如下 ZooKeeper(connectString, sessionTimeout, watcher): ZooKee ...
- MongoDB -- JAVA基本API操作
package com.example.mongodb.mongodb.demo; import com.mongodb.MongoClient; import com.mongodb.client. ...
- 1.java soap api操作和发送soap消息
转自:https://blog.csdn.net/lbinzhang/article/details/84721359 1. /** * soap请求 * * @return * @throws Ex ...
- es之java各种查询操作
matchAllQuery 匹配所有文档 queryStringQuery 基于Lucene的字段检索 wildcardQuery 通配符查询匹配多个字符,?匹配1个字符* termQuery 词条查 ...
随机推荐
- 数据库DDL与DML对应含义
DDL:指的是操作数据库.表.字段的相关语句,例如:create.alter.drop DML:指的是对表中的数据进行增删改的操作,例如:insert.update.delete 查询语句书写顺序:s ...
- GAN实战笔记——第二章自编码器生成模型入门
自编码器生成模型入门 之所以讲解本章内容,原因有三. 生成模型对大多数人来说是一个全新的领域.大多数人一开始接触到的往往都是机器学习中的分类任务--也许因为它们更为直观:而生成模型试图生成看起来很逼真 ...
- 《手把手教你》系列技巧篇(三十三)-java+ selenium自动化测试-单选和多选按钮操作-上篇(详解教程)
1.简介 在实际自动化测试过程中,我们同样也避免不了会遇到单选和多选的测试,特别是调查问卷或者是答题系统中会经常碰到.因此宏哥在这里直接分享和介绍一下,希望小伙伴或者童鞋们在以后工作中遇到可以有所帮助 ...
- SharkCTF2021 pwn“初见”1
(无内鬼 今日不想学了 水一篇) nc nc nc easyoverflow Intoverflow
- 【c++ Prime 学习笔记】第8章 IO库
C++语言不直接处理输入输出,而是通过标准库中的一组类来处理IO 1.2节介绍的IO库: istream(输入流)类型,提供输入 ostream(输出流)类型,提供输出 cin,是istream对象, ...
- 痞子衡嵌入式:超级下载算法RT-UFL v1.0在Keil MDK下的使用
痞子衡主导的"学术"项目 <RT-UFL - 一个适用全平台i.MXRT的超级下载算法设计> v1.0 版发布近 4 个月了,部分客户已经在实际项目开发调试中用上了这个 ...
- spring security中动态更新用户的权限
在程序的执行过程中,有时有这么一种需求,需要动态的更新某些角色的权限或某些人对应的权限,当前在线的用户拥有这个角色或拥有这个权限时,在不退出系统的情况下,需要动态的改变的他所拥有的权限. 需求:张三 ...
- TVS管相关知识
在设计中,使用到了TVS管,在之前的设计中没有特别关注TVS管.今天查了一些资料,算是简单的有个了解. TVS管是一种保护器件.它的英文全称为 transient voltage suppressor ...
- linux下的IO模型---学习笔记
1.linux文件系统和缓存 文件系统接口 文件系统-一种把数据组织成文件和目录的存储方式,提供了基于文件的存取接口,并通过文件权限控制访问. 存储层次 文件系统缓存 主存(通常时DRAM)的一块区域 ...
- Linux多线程编程之详细分析
线程?为什么有了进程还需要线程呢,他们有什么区别?使用线程有什么优势呢?还有多线程编程的一些细节问题,如线程之间怎样同步.互斥,这些东西将在本文中介绍.我见到这样一道面试题: 是否熟悉POSIX多线程 ...