JavaAPI-环境准备
新建Maven工程
添加依赖 创建POM文件
xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yooomecloud</artifactId>
<groupId>com.yooome.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-config-elasticsearch-9200</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--elasticsearch需要依赖-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.7.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.7.0</version>
</dependency>
</dependencies>
</project>
JavaAPI-索引-创建
java
@GetMapping("/elsa/search/{id}")
public String GetElasticsearch(@PathVariable("id") Integer id) throws IOException {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
System.out.println(client);
// 创建索引 - 请求对象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("user3");
// 发送请求,获取响应
CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = response.isAcknowledged();
System.out.println("操作状态:" + acknowledged);
// 关闭客户端连接
client.close();
return "get elastic search dsgs " + "server port " + serverPort + " ack " + id + " acknowledged " + acknowledged;
}
JavaAPI-索引-查询 & 删除
查询
java
@GetMapping("elas/search/user")
public String GetIndexResponse() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
return "aliases: " + response.getAliases() + " mappings: " + response.getMappings() + " settings: " + response.getSettings();
}
删除
java
@GetMapping("/elas/delete")
public String DeleteIndexResponse() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteIndexRequest request = new DeleteIndexRequest("user3");
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
return "response: " + response.isAcknowledged();
}
JavaAPI-文档-新增 & 修改
重构
上下文由于频繁使用以下连接 Elasticsearch 和 关闭它的代码,于是个人对它进行重构。
新增
java
@GetMapping("/elas/create/doc")
public String CreateElasticsearchIndex() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
IndexRequest request = new IndexRequest();
request.index("user4").id("1000");
//创建数据对象
User user = new User();
user.setAge(18);
user.setName("zhangsan");
user.setSex("男");
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
// 添加文档数据,数据格式为 JSON 格式
request.source(s, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println("_index:" + response.getIndex());
System.out.println("_id:" + response.getId());
System.out.println("_result:" + response.getResult());
return "_index:" + response.getIndex() + "_id:" + response.getId() + "_result:" + response.getResult();
}
修改
java
@GetMapping("/elas/update/doc")
public String UpdateElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 修改文档 - 请求对象
UpdateRequest request = new UpdateRequest();
// 修改配置参数
request.index("user4").id("1000");
// 设置请求体,对数据修改
request.doc(XContentType.JSON, "sex", "女");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
return "index " + response.getIndex() + " _id " + response.getId() + " _result " + response.getResult();
}
JavaAPI-文档-查询 & 删除
查询
java
@GetMapping("/elas/search/doc")
public String SearchElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建请求对象
GetRequest request = new GetRequest();
// 客户端发送请求,获取响应对象
request.index("user4").id("1000");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
client.close();
return "_index = " + response.getIndex() + " _type = " + response.getType() + " _id = " + response.getId() + " source = " + response.getSource();
}
删除
java
@GetMapping("/elas/delete/doc")
public String DeleteElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建请求对象
DeleteRequest request = new DeleteRequest();
// 客户端发送请求,获取响应对象
request.index("user4").id("1000");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
client.close();
return delete.toString();
}
JavaAPI-文档-批量新增 & 批量删除
批量新增
java
@GetMapping("/elas/batch/add")
public String BatchAddElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建添加对象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user5").id("1001").source(XContentType.JSON,"name","zhangsan"));
request.add(new IndexRequest().index("user5").id("1002").source(XContentType.JSON,"name","lisi"));
request.add(new IndexRequest().index("user5").id("1003").source(XContentType.JSON,"name","wangwu"));
//客户端发送请求,获取响应对象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
return "took = " + responses.getTook() +" item = " + responses.getItems();
}
批量删除
java
@GetMapping("/elas/batch/delete")
public String BatchDeleteElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建添加对象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user5").id("1001"));
request.add(new DeleteRequest().index("user5").id("1002"));
request.add(new DeleteRequest().index("user5").id("1003"));
//客户端发送请求,获取响应对象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
return "took = " + responses.getTook() +" item = " + responses.getItems();
}
JavaAPI-文档-高级查询-全量查询
先批量增加数据
java
@GetMapping("/elas/batch/add")
public String BatchAddElasDoc() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建添加对象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user5").id("1001").source(XContentType.JSON,"name","zhangsan"));
request.add(new IndexRequest().index("user5").id("1002").source(XContentType.JSON,"name","lisi"));
request.add(new IndexRequest().index("user5").id("1003").source(XContentType.JSON,"name","wangwu"));
request.add(new IndexRequest().index("user5").id("1004").source(XContentType.JSON,"name","zhaoliu"));
request.add(new IndexRequest().index("user5").id("1005").source(XContentType.JSON,"name","hanqi"));
//客户端发送请求,获取响应对象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
return "took = " + responses.getTook() +" item = " + responses.getItems();
}
查询所有索引数据
java
@GetMapping("/elas/batch/search/index")
public String BatchSearchElasIndex() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建添加对象
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user5");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查询所有数据
sourceBuilder.query(QueryBuilders.matchAllQuery());
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
}
JavaAPI-文档-高级查询-分页查询 & 条件查询 & 查询排序
条件查询
java
@GetMapping("/elas/best/search/index")
public String BestSearchElasIndex() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user5");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("name", "zhangsan"));
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
}
分页查询
java
@GetMapping("/elas/page/search/index")
public String PageSearchElasIndex() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user5");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 分页查询
// 当前页其实索引(第一条数据的顺序号), from
sourceBuilder.from(0);
// 每页显示多少条 size
sourceBuilder.size(2);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
return "took = " + response.getTook() + " time out = "+ response.isTimedOut() + " total hits = " + hits.getTotalHits() + " max score = " + hits.getMaxScore();
}
查询排序
java
@GetMapping("/elas/sort/order")
public String SortOrderElas() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 排序
sourceBuilder.sort("age", SortOrder.ASC);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
return "";
}
JavaAPI-文档-高级查询-组合查询 & 范围查询
组合查询
java
@GetMapping("/elas/match/query")
public void matchQuery() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必须包含
boolQueryBuilder.must(QueryBuilders.matchQuery("age", "20"));
// 一定不含
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
// 可能包含
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
}
范围查询
java
@GetMapping("/elas/range/query")
public void RangeQuery() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
// 大于等于
//rangeQuery.gte("30");
// 小于等于
rangeQuery.lte("40");
sourceBuilder.query(rangeQuery);
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
}
JavaAPI-文档-高级查询-模糊查询 & 高亮查询
模糊查询
java
@GetMapping("/elas/fuzzy/query")
public void fuzzyQuery() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.fuzzyQuery("name", "wangw").fuzziness(Fuzziness.ONE));
request.source(sourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 查询匹配
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
}
高亮查询
java
@GetMapping("/elas/high/query")
public void HighLightSearch() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 高亮查询
SearchRequest request = new SearchRequest().indices("user");
//2.创建查询请求体构建器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//构建查询方式:高亮查询
TermsQueryBuilder termsQueryBuilder =
QueryBuilders.termsQuery("name","lisi");
//设置查询方式
sourceBuilder.query(termsQueryBuilder);
//构建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");//设置标签前缀
highlightBuilder.postTags("</font>");//设置标签后缀
highlightBuilder.field("name");//设置高亮字段
//设置高亮构建对象
sourceBuilder.highlighter(highlightBuilder);
//设置请求体
request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
SearchHits hits = response.getHits();
System.out.println("took::"+response.getTook());
System.out.println("time_out::"+response.isTimedOut());
System.out.println("total::"+hits.getTotalHits());
System.out.println("max_score::"+hits.getMaxScore());
System.out.println("hits::::>>");
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
//打印高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(highlightFields);
}
System.out.println("<<::::");
}
JavaAPI-文档-高级查询-最大值查询 & 分组查询
最大值查询
java
@GetMapping("/elas/maxvalue/query")
public void MaxValueSearch() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 高亮查询
SearchRequest request = new SearchRequest().indices("user");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
//设置请求体
request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
SearchHits hits = response.getHits();
System.out.println(response);
for (SearchHit hit : hits) {
System.out.println(hit);
}
}
分组查询
java
@GetMapping("/elas/group/query")
public void GroupSearch() throws IOException {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 高亮查询
SearchRequest request = new SearchRequest().indices("user");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
//设置请求体
request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
SearchHits hits = response.getHits();
System.out.println(response);
for (SearchHit hit : hits) {
System.out.println(hit);
}
}