ES使用Java API操作ES宝典(7.x版本及其以下)
Posted 老坛聊开发
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES使用Java API操作ES宝典(7.x版本及其以下)相关的知识,希望对你有一定的参考价值。
大家好,我是老坛。
本篇文章全部代码资源请关注同名公众号:老坛聊开发
回复:"7.x模板" 即可获取
Elasticsearch是一个分布式的RESTful 风格的搜索和数据分析引擎,它使用方便,查询速度快,因此也被越来越多的开发人员使用。
在Java项目中,使用ES的场景也十分常见。除了作为某些特定资源的存储之外也可以作为像ELK这样的日志收集系统里的存储引擎。总之,对于非关系型而查找需求较多的场景,ES的表现还是非常不错的。
那今天老坛就带大家看一看如何使用Java API来操作ES。
当前文档只限于ES的版本在7.x及其以下的情况,如果是8.x的可以去看我的另一篇文档:
【ES使用】Java API操作ES宝典(8.x版本)https://blog.csdn.net/qq_34263207/article/details/127847033
目录
1.准备工作
在真正使用es api之前,还有一些准备工作要去做,分别是引入依赖和写好配置文件
1.1引入依赖
对于7.x及其以下的版本,spring data这边是支持的,所以可以根据自己ES的具体版本来引入匹配版本的spring data starter,具体如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
关于如何去查看spring data与ES的版本匹配关系,大家可以去看我的这篇文章,这里便不再赘述了。
【ES知识】es版本与java api版本对照一览https://blog.csdn.net/qq_34263207/article/details/127790216
1.2配置文件
接下来就是去写配置文件了。我们要连接ES所要用到的ip和port,用户名和密码这些信息建议大家都写在自己的yml里,方便维护:
es:
address: 127.0.0.1
port: 9200
scheme: http
username: admin
password: admin
接下来我们要写一个config文件来使用这些配置,具体代码如下:
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchConfig
@Value("$es.address")
String address;
@Value("$es.port")
Integer port;
@Value("$es.scheme")
String scheme;
@Value("$es.username")
String username;
@Value("$es.password")
String password;
@Bean
public RestHighLevelClient esRestClient()
RestClientBuilder builder = null;
builder = RestClient.builder(new HttpHost(address, port, scheme));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
这个是无用户名和密码版本的配置文件,大家可以直接拿走使用。
下面贴一下需要配置用户名和密码的config文件:
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchConfig
@Value("$es.address")
String address;
@Value("$es.port")
Integer port;
@Value("$es.scheme")
String scheme;
@Value("$es.username")
String username;
@Value("$es.password")
String password;
@Bean
public RestHighLevelClient esRestClientWithCred()
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(address, port, scheme))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback()
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder)
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
);
RestHighLevelClient esClient = new RestHighLevelClient(restClientBuilder);
return esClient;
按需来取即可。
2. 简单操作
也就是最基本的CRUD了,但是这部分介绍的都是只针对一条数据的CRUD操作,都是通过id来去进行的,比较简单。而操作这些所使用到的类也比较有规律,这里我给大家画一张图方便理解:
RestHighLevelClient是我们所有操作的核心,它也是在我们config里面写好的,等着被注入就可以了。对于每一种操作都有其相应的request和response,我们在request里面填充需要做的操作,用response接收结果。下面举例来介绍这些操作。
更多优质文章资源请关注同名公众号:老坛聊开发
先介绍一下我用到的实体对象:
@Data
public class TextBook
String bookName;
String author;
Integer num;
对应的索引数据为:
"_index": "textbook",
"_id": "kIwXeYQB8iTYJNkI986Y",
"_source":
"bookName": "This is a test doc",
"author": "老坛",
"num": 20
2.1 插入数据
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public void insertSingle(String id) throws IOException
IndexRequest request = new IndexRequest(index);
request.id(id);
// 要插入的实体
TextBook textBook = new TextBook();
textBook.setBookName("老坛聊开发");
textBook.setAuthor("老坛");
textBook.setNum(20);
request.source(JSON.toJSONString(textBook), XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
log.info("返回状态:" + indexResponse.status().getStatus());
我们需要将RestHighLevelClient注入进来,然后就可以操作了。
2.2 查询数据
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public void grepSingle(String id) throws IOException
GetRequest getRequest = new GetRequest(index);
getRequest.id(id);
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
String json = getResponse.getSourceAsString();
TextBook textBook = JSONObject.parseObject(json, TextBook.class);
log.info("返回结果为:" + JSON.toJSONString(textBook));
这里是使用id查询单条数据,相当于sql的getByPrimaryKey。
2.3 修改数据
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public void updateSingle(String id) throws IOException
GetRequest getRequest = new GetRequest(index);
getRequest.id(id);
// 先查看是否包含该数据,以防报错
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
if(exists)
UpdateRequest updateRequest = new UpdateRequest(index, id);
TextBook textBook = new TextBook();
// 要更新的实体
textBook.setBookName("老坛聊开发");
textBook.setAuthor("老坛");
updateRequest.doc(JSON.toJSONString(textBook), XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
log.info("返回状态:" + updateResponse.status().getStatus());
这里先用exist方法查询了一下该条数据是否存在,存在的话再去修改数据。
2.4 删除数据
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public void deleteSingle(String id) throws IOException
DeleteRequest deleteRequest = new DeleteRequest(index);
deleteRequest.id(id);
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
log.info("返回状态:" + deleteResponse.status().getStatus());
3 复杂查询
3.1 整体介绍
下面介绍复杂查询,也是我们比较常用的ES查询方式,这里如果大家有一定的ES语法基础会更方便的理解下面的内容,想了解ES基础语法可以去看我的这篇文章:
【ES知识】ES基础查询语法一览https://blog.csdn.net/qq_34263207/article/details/127849806
老规矩,先上图:
该图描绘了我们在复杂查询时会涉及到的类:一样是使用RestHighLevelClient,然后通过SearchRequest进行操作,SearchRequest又需要SearchSourceBuilder,而SearchSourceBuilder需要通过QueryBuilder完成构建,图中最下面一行列出了几种常用的QueryBuilder,基本上和我们ES查询的语法是直接相关的。最后SearchResponse返回结果。
更多优质文章资源请关注同名公众号:老坛聊开发
下面给出查询的模板代码:
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public List<TextBook> grepTextBook() throws IOException
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("author", "老坛");
searchSourceBuilder.query(matchQueryBuilder);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.source(searchSourceBuilder);
List<TextBook> textBookList = new ArrayList<>();
//执行操作
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
if (Objects.nonNull(searchResponse))
SearchHits searchHits = searchResponse.getHits();
for (int i = 0; i < searchHits.getHits().length; i++)
String str = searchHits.getHits()[i].getSourceAsString();
System.out.println(str);
textBookList.add(JSON.parseObject(str, TextBook.class));
return textBookList;
整个查询代码的核心实际上只有这一行:
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("author", "老坛");
因为只有QueryBuilder决定了你要怎么去进行查询,其它的都是模板,可以不动。
3.2 QueryBuilder说明
下面我们来一一介绍几种常用的QueryBuilder:
3.2.1 MatchQueryBuilder
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("author", "老坛");
对应了ES的match查询,它等价的ES语法就是:
GET textbook/_search
"query":
"match":
"author":"老坛"
3.2.2 MatchPhraseQueryBuilder
MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("bookName", "老坛");
对应了ES的match_phrase查询,它等价的ES语法就是:
GET textbook/_search
"query":
"match_phrase":
"bookName":"老坛"
3.2.3 MultiMatchQueryBuilder
MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("老坛", "author","bookName");
对应了ES的multi_match查询,它等价的ES语法就是:
GET textbook/_search
"query":
"multi_match":
"query": "老坛",
"fields": ["author","bookName"]
3.2.4 TermQueryBuilder
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("author", "老坛");
对应了ES的term查询,它等价的ES语法就是:
GET textbook/_search
"query":
"term":
"author":
"value": "老坛"
3.2.5 TermsQueryBuilder
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("author", "老","坛");
对应了ES的terms查询,它等价的ES语法就是:
GET textbook/_search
"query":
"terms":
"author": ["老","坛"]
3.2.6 FuzzyQueryBuilder
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("bookName", "老坛");
对应了ES的fuzzy查询,它等价的ES语法就是:
GET textbook/_search
"query":
"fuzzy":
"bookName":"老坛"
我们只要根据自己需要选择不同的builder去查询就可以了
3.2.7 RangeQueryBuilder
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("num")
.gt(10)
.lt(20);
对应了ES的range查询,它等价的ES语法就是:
GET textbook/_search
"query":
"range":
"num":
"lt":20,
"gt":10
更多优质文章资源请关注同名公众号:老坛聊开发
3.3 bool查询
bool查询也是我们使用es中比较常见的,当我们需要查询多个条件时,就会需要:
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("bookName", "老坛");
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("author", "老坛");
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
.must(matchQueryBuilder)
.should(termQueryBuilder);
所对应的ES语法为:
GET textbook/_search
"query":
"bool":
"must":
"match":
"bookName":"老坛"
,
"should":
"term":
"author":"老坛"
3.4 排序和分页
还用最开始的match举例,这里在此基础上添加了排序和分页两个限制:
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class ESTest
@Resource
RestHighLevelClient restHighLevelClient;
String index = "index";
@Test
public List<TextBook> grepTextBook() throws IOException
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("bookName", "老坛");
searchSourceBuilder.query(matchQueryBuilder);
// 分页参数
searchSourceBuilder.sort("num", SortOrder.DESC);
searchSourceBuilder.from(1);
searchSourceBuilder.size(100);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.source(searchSourceBuilder);
List<TextBook> textBookList = new ArrayList<>();
//执行操作
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
if (Objects.nonNull(searchResponse))
SearchHits searchHits = searchResponse.getHits();
for (int i = 0; i < searchHits.getHits().length; i++)
String str = searchHits.getHits()[i].getSourceAsString();
System.out.println(str);
textBookList.add(JSON.parseObject(str, TextBook.class));
return textBookList;
排序和分页主要体现在这几行:
// 分页参数
searchSourceBuilder.sort("num", SortOrder.DESC);
searchSourceBuilder.from(1);
searchSourceBuilder.size(100);
可以看到这是一个按照num字段的降序搜索,并且是按照页容量为100进行分页,取第二页。
所对应的ES语法为:
GET textbook/_search
"query":
"match":
"bookName":"老坛"
,
"from":0,
"size":100,
"sort":
"num":
"order":"desc"
4.代码模板
本篇文章中介绍的全部es操作老坛已整理成模板项目了:
请关注同名公众号:老坛聊开发
并回复:"7.x模板" 获取代码模板
只要大家根据自己的实际环境修改配置即可直接跑起来啦,亲测有效!
5. 总结
到这里Java对ES的操作基本上聊的差不多了,题主这里介绍的未必详尽,只是一些我们通常会用到的操作,如果还想详细了解更多的内容请阅读官方文档:
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/7.17/java-client-javadoc.html
另外,题主这里只是为了给大家讲明白如何使用举了几个例子,并不一定效率最高或者使用常见最为恰当,还是需要大家学习一下ES的语法根据自己的实际业务场景去选用,谢谢大家~
Elasticsearch——使用Java API实现ES中的索引映射文档操作
文章目录:
1.开篇
在上一篇文章中,对ES中的创建/查看/删除索引、创建定义映射、创建/查看/修改/删除文档的这些操作有了一定的了解认识,但是是通过Postman + JSON串的方法来实现的。文章链接:https://blog.csdn.net/weixin_43823808/article/details/119911746
那么,这篇文章,仍然是对ES中的索引、映射、文档进行操作,只是方法换成了Java API。
2.案例详解
首先需要创建一个maven工程,必然要添加ES相关的依赖。
同时双击ES安装目录的bin目录下的 elasticsearch.bat ,先启动ES服务端。
<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>
2.1 创建ES客户端:完成与ES服务端的连接
后面的一二十个案例都是依照这个模板代码来的。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestClient {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//关闭ES客户端
esClient.close();
}
}
2.2 创建索引
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import java.io.IOException;
/**
*
*/
public class ESTestIndexCreate {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建索引 --- 请求对象
CreateIndexRequest request = new CreateIndexRequest("user");
//发送请求 --- 获取响应
CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
//响应状态
boolean acknowledged = response.isAcknowledged();
System.out.println("索引操作:" + acknowledged);
//关闭ES客户端
esClient.close();
}
}
2.3 查看索引
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import java.io.IOException;
/**
*
*/
public class ESTestIndexSearch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询索引 --- 请求对象
GetIndexRequest request = new GetIndexRequest("user");
//发送请求 --- 获取响应
GetIndexResponse response = esClient.indices().get(request, RequestOptions.DEFAULT);
//响应状态
System.out.println(response.getAliases());
System.out.println(response.getMappings());
System.out.println(response.getSettings());
//关闭ES客户端
esClient.close();
}
}
2.4 删除索引
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestIndexDelete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除索引 --- 请求对象
DeleteIndexRequest request = new DeleteIndexRequest("user");
//发送请求 --- 获取响应
AcknowledgedResponse response = esClient.indices().delete(request,RequestOptions.DEFAULT);
//响应状态
System.out.println(response.isAcknowledged());
//关闭ES客户端
esClient.close();
}
}
2.5 创建文档
索引有了,就相当于有了数据库。接下来就需要向数据库中建表、添加数据。建表自然要有表结构(有哪些属性、这些属性分别都是什么数据类型),也就是ES中的映射,在Java代码中就可以采用实体类来实现。
package com.szh.es;
/**
*
*/
public class User {
private String name;
private String sex;
private Integer age;
//getter and setter
}
package com.szh.es;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
*
*/
public class ESTestDocInsert {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//创建文档 --- 请求对象
IndexRequest request = new IndexRequest();
//设置索引及索引中文档的唯一性标识id(如果不指定,则ES会默认随机生成一个id)
request.index("user").id("1001");
//创建数据对象(文档内容)
User user = new User();
user.setName("张起灵");
user.setSex("man");
user.setAge(21);
//向ES中插入数据,必须将数据格式转换为JSON
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
//发送请求 --- 获取响应
IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
2.6 修改文档
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
*
*/
public class ESTestDocUpdate {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//修改文档 --- 请求对象
UpdateRequest request = new UpdateRequest();
//配置修改参数 --- 表示要修改user索引中id为1001的文档内容
request.index("user").id("1001");
//将修改后的内容,以JSON格式写入请求体中
request.doc(XContentType.JSON,"age",18);
//发送请求 --- 获取响应
UpdateResponse response = esClient.update(request,RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
2.7 查看文档
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestDocSearch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//查询文档 --- 请求对象
GetRequest request = new GetRequest();
//设置请求参数 --- 表示要查询user索引中id为1001的文档内容
request.index("user").id("1001");
//发送请求 --- 获取响应
GetResponse response = esClient.get(request,RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
//关闭ES客户端
esClient.close();
}
}
2.8 删除文档
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestDocDelete {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//删除文档 --- 请求对象
DeleteRequest request = new DeleteRequest();
//设置请求参数 --- 表示要删除user索引中id为1001的文档
request.index("user").id("1001");
//发送请求 --- 获取响应
DeleteResponse response = esClient.delete(request,RequestOptions.DEFAULT);
System.out.println(response.getResult());
//关闭ES客户端
esClient.close();
}
}
2.9 批量创建文档
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
*
*/
public class ESTestDocInsertBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量新增文档 --- 请求对象
BulkRequest request = new BulkRequest();
//以JSON格式批量新增文档 --- 存入请求体中
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张起灵","sex","boy","age",21));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "小哥","sex","boy","age",18));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "小宋","sex","boy","age",20));
//发送请求 --- 获取响应
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
//关闭ES客户端
esClient.close();
}
}
2.10 批量删除文档
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
/**
*
*/
public class ESTestDocDeleteBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量删除文档 --- 请求对象
BulkRequest request = new BulkRequest();
//将要删除的文档id存入请求体中
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
//发送请求 --- 获取响应
BulkResponse response = esClient.bulk(request,RequestOptions.DEFAULT);
System.out.println(response.getTook());
System.out.println(response.getItems());
//关闭ES客户端
esClient.close();
}
}
2.11 全量查询
因为上面两个代码案例分别进行了批量创建、批量删除。所以这里首先执行一次批量创建的代码,确保索引中有多条数据供我们查询。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
/**
*
*/
public class ESTestDocInsertBatch {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//批量新增文档 --- 请求对象
BulkRequest request = new BulkRequest();
//以JSON格式批量新增文档 --- 存入请求体中
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张起灵","sex","boy","age",21));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "小哥","sex","boy","age",18));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "小宋","sex","boy","age",20));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "冷少","sex","boy","age",25));
request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "Java软件工程师","sex","girl","age",40));
//发送请求 --- 获取响应
BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.getTook());
//关闭ES客户端
esClient.close();
}
}
下面首先进行全量查询操作。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//1.查询索引中的全部文档 --- matchAllQuery 全量查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体 --- 存入搜索请求对象中
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.12 条件查询
做匹配查询,查询年龄age=21的文档内容。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//2.条件查询--- termQuery age=21
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体 --- 存入搜索请求对象中
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",21)));
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.13 分页查询
做全量查询,对查询结果进行分页显示,每页2条数据,查询第1页。
查看第几页:(页码 - 1)*每页条数
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//3.分页查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.from(0);
builder.size(2);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.14 排序查询
做全量查询,对查询结果中的年龄age字段做降序排序。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//4.对查询结果进行排序
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.sort("age", SortOrder.DESC);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.15 过滤字段查询
做全量查询,同时排除性别sex字段。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//5.过滤字段
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
String[] excludes = {"sex"};
String[] includes = {};
builder.fetchSource(includes,excludes);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.16 组合条件查询
查询年龄 age=18 或者 name=张起灵 的文档内容。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//6.组合查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(QueryBuilders.matchQuery("age",18));
boolQueryBuilder.should(QueryBuilders.matchQuery("name","张起灵"));
builder.query(boolQueryBuilder);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.17 范围查询
查询年龄age字段大于等于18、小于25的文档内容。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//7.范围查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(18);
rangeQueryBuilder.lt(25);
builder.query(rangeQueryBuilder);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.18 模糊查询
builder.query(QueryBuilders.fuzzyQuery("name","小张").fuzziness(Fuzziness.ONE)); 最后的这个枚举类型 ONE,表示查询结果中允许与我定义的name字段为 小张 相差1个字符,也就是说,查询出的结果要么包含 小、要么包含 张、或者就是小张。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//8.模糊查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
//FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name","小张");
//fuzzyQueryBuilder.fuzziness(Fuzziness.ONE);
//builder.query(fuzzyQueryBuilder);
//上面三行代码 等价于 下面这行代码
builder.query(QueryBuilders.fuzzyQuery("name","小张").fuzziness(Fuzziness.ONE));
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.19 聚合查询
查询age字段,年龄最大的文档内容。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//9.聚合查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
2.20 分组查询
根据age年龄字段进行group分组查询。
package com.szh.es;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import java.io.IOException;
/**
*
*/
public class ESTestDocQuery {
public static void main(String[] args) throws IOException {
//创建ES客户端
RestHighLevelClient esClient = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost",9200,"http"))
);
//10.分组查询
//创建搜索请求对象
SearchRequest request = new SearchRequest();
//设置参数 --- 表示查询哪个索引中的文档内容
request.indices("user");
//构建查询的请求体
SearchSourceBuilder builder = new SearchSourceBuilder();
AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
builder.aggregation(aggregationBuilder);
//将构建好的查询请求体存入搜索请求对象中
request.source(builder);
//发送请求 --- 获取响应
SearchResponse response = esClient.search(request,RequestOptions.DEFAULT);
//获取查询到的结果集
SearchHits hits = response.getHits();
System.out.println(hits.getTotalHits()); //结果集的条数
System.out.println(response.getTook()); //总耗时
//遍历结果集
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
//关闭ES客户端
esClient.close();
}
}
以上是关于ES使用Java API操作ES宝典(7.x版本及其以下)的主要内容,如果未能解决你的问题,请参考以下文章
Helm安装带验证的ElasticSearch 6.x 7.x 集群
Elasticsearch - Java API 操作 ES7.15.0ES7.x 索引,文档;高级搜索