Elasticsearch之JAVA API操作
Posted 爱上口袋的天空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Elasticsearch之JAVA API操作相关的知识,希望对你有一定的参考价值。
1、JavaAPI-环境准备
1.1、创建一个springboot项目
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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>kgf-java-learning</artifactId> <groupId>com.kgf.learning</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../kgf-java-learning/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.kgf.es7.8</groupId> <artifactId>kgf-es7.8-api</artifactId> <properties> <!--自定义elasticsearch版本--> <elasticsearch.version>7.8.0</elasticsearch.version> <lombok.version>1.18.16</lombok.version> <fastjson.version>1.2.75</fastjson.version> </properties> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--引入lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入Juntil单元测试 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--jsoup解析网页,tiks解析视频音乐--> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.2.11.RELEASE</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
ElasticConfig.java如下:
package com.kgf.es.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticConfig { @Bean public RestHighLevelClient restHighLevelClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")) ); return client; } }
1.2、ESApplication.java如下
package com.kgf.es; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ESApplication { public static void main(String[] args) { SpringApplication.run(ESApplication.class,args); } }
2、JavaAPI-索引-创建
2.1、在一个Junit测试类创建索引
package es7; import com.kgf.es.ESApplication; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.io.IOException; @RunWith(SpringRunner.class) @SpringBootTest(classes = ESApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class EsApplicationTest { @Resource private RestHighLevelClient restHighLevelClient; /*** * 创建索引 */ @Test public void createIndexTest(){ try { //创建索引对象 CreateIndexRequest indexRequest = new CreateIndexRequest("user"); //客户端执行请求 CreateIndexResponse response = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT); boolean acknowledged = response.isAcknowledged(); // 响应状态 System.out.println("操作状态 = " + acknowledged); } catch (IOException e) { e.printStackTrace(); } } }
执行:
查看索引:
3、索引-查询 & 删除
3.1、查询
/*** * 查询索引 */ @Test public void getIndexTest(){ try { // 查询索引 - 请求对象 GetIndexRequest request = new GetIndexRequest("user"); // 发送请求,获取响应 GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT); System.out.println("aliases:"+response.getAliases()); System.out.println("mappings:"+response.getMappings()); System.out.println("settings:"+response.getSettings()); } catch (IOException e) { e.printStackTrace(); } }
后台打印:
aliases:{user=[]} mappings:{user=org.elasticsearch.cluster.metadata.MappingMetadata@872c984c} settings:{user={"index.creation_date":"1624163950299","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.uuid":"XvPUSw3rR7CjmrGk0BtdCw","index.version.created":"7080099"}}
3.2、删除
/*** * 删除索引 */ @Test public void DelIndexTest(){ try { // 删除索引 - 请求对象 DeleteIndexRequest request = new DeleteIndexRequest("user"); // 发送请求,获取响应 AcknowledgedResponse response = restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT); // 操作结果 System.out.println("操作结果 : " + response.isAcknowledged()); } catch (IOException e) { e.printStackTrace(); } }
后台打印:
操作结果 : true
4、JavaAPI-文档-新增 & 修改
4.1、新增
/*** * 添加文档 */ @Test public void addDocumentTest(){ try { // 新增文档 - 请求对象 IndexRequest request = new IndexRequest(); // 设置索引及唯一性标识 request.index("user").id("1001"); // 创建数据对象 User user = new User(); user.setName("zhangsan"); user.setAge(30); user.setSex("男"); ObjectMapper objectMapper = new ObjectMapper(); String productJson = objectMapper.writeValueAsString(user); // 添加文档数据,数据格式为 JSON 格式 request.source(productJson, XContentType.JSON); // 客户端发送请求,获取响应对象 IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT); //打印结果信息 System.out.println("_index:" + response.getIndex()); System.out.println("_id:" + response.getId()); System.out.println("_result:" + response.getResult()); } catch (IOException e) { e.printStackTrace(); } }
后台打印:
4.2、修改
/*** * 修改文档信息 */ @Test public void updateDocument(){ try { // 修改文档 - 请求对象 UpdateRequest request = new UpdateRequest(); // 配置修改参数 request.index("user").id("1001"); // 设置请求体,对数据进行修改 request.doc(XContentType.JSON, "sex", "女"); // 客户端发送请求,获取响应对象 UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT); System.out.println("_index:" + response.getIndex()); System.out.println("_id:" + response.getId()); System.out.println("_result:" + response.getResult()); } catch (Exception e) { e.printStackTrace(); } }
后台打印:
5、文档-查询 & 删除
5.1、查询文档
/*** * 查询文档信息 */ @Test public void queryDocument(){ try { //1.创建请求对象 GetRequest request = new GetRequest().index("user").id("1001"); //2.客户端发送请求,获取响应对象 GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT); //打印结果信息 System.out.println("_index:" + response.getIndex()); System.out.println("_type:" + response.getType()); System.out.println("_id:" + response.getId()); System.out.println("source:" + response.getSourceAsString()); } catch (Exception e) { e.printStackTrace(); } }
后台打印:
_index:user _type:_doc _id:1001 source:{"name":"zhangsan","age":30,"sex":"男"} Process finished with exit code 0
5.2、删除
/*** * 删除文档操作 * @throws IOException */ @Test public void delDocumentTest() throws IOException { //创建请求对象 DeleteRequest request = new DeleteRequest().index("user").id("1001"); //客户端发送请求,获取响应对象 DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT); //打印信息 System.out.println(response.toString()); }
后台打印:
DeleteResponse[index=user,type=_doc,id=1001,version=16,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}] Process finished with exit code 0
6、文档-批量新增 & 批量删除
6.1、批量新增
/*** * 测试批量插入操作 * @throws IOException */ @Test public void bulkInsertRequestTest() throws IOException { //创建批量新增请求对象 BulkRequest request = new BulkRequest(); request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan")); request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi")); request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu")); //客户端发送请求,获取响应对象 BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); //打印结果信息 System.out.println("took:" + responses.getTook()); System.out.println("items:" + responses.getItems()); }
后台打印
took:294ms items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@2beee7ff Process finished with exit code 0
6.2、批量删除
/*** * 测试批量插入操作 * @throws IOException */ @Test public void bulkDeleteRequestTest() throws IOException { //创建批量删除请求对象 BulkRequest request = new BulkRequest(); 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 responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); //打印结果信息 System.out.println("took:" + responses.getTook()); System.out.println("items:" + responses.getItems()); }
后台打印
took:108ms items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@7b02881e Process finished with exit code 0
7、文档-高级查询-全量查询
7.1、先批量增加数据
/*** * 测试批量插入操作 * @throws IOException */ @Test public void bulkInsertRequestTest() throws IOException { //创建批量新增请求对象 BulkRequest request = new BulkRequest(); request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age", "10", "sex","女")); request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age", "30", "sex","女")); request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu1", "age", "40", "sex","男")); request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "wangwu2", "age", "20", "sex","女")); request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "wangwu3", "age", "50", "sex","男")); request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu4", "age", "20", "sex","男")); //客户端发送请求,获取响应对象 BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); //打印结果信息 System.out.println("took:" + responses.getTook()); System.out.println("items:" + responses.getItems()); }
后台打印
took:168ms items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@2beee7ff Process finished with exit code 0
查询所有索引数据
/*** * 查询所有索引数据 * @throws IOException */ @Test public void searchRequestTest() throws IOException { // 创建搜索请求对象 SearchRequest request = new SearchRequest(); request.indices("user"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 查询所有数据 sourceBuilder.query(QueryBuilders.matchAllQuery()); request.source(sourceBuilder); SearchResponse response = restHighLevelClient.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("<<========"); }
后台打印
took:2ms timeout:false total:6 hits MaxScore:1.0 hits========>> {"name":"zhangsan","age":"10","sex":"女"} {"name":"lisi","age":"30","sex":"女"} {"name":"wangwu1","age":"40","sex":"男"} {"name":"wangwu2","age":"20","sex":"女"} {"name":"wangwu3","age":"50","sex":"男"} {"name":"wangwu4","age":"20","sex":"男"} <<======== Process finished with exit code 0
8、文档-高级查询-分页查询 & 条件查询 & 查询排序
8.1、条件查询
/*** * 条件查询 * @throws IOException */ @Test public void queryByConditiontest() throws IOException { // 创建搜索请求对象 SearchRequest request = new SearchRequest(); request.indices("user"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.termQuery("age", "30")); request.source(sourceBuilder); SearchResponse response = restHighLevelClient.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("<<========"); }
后台打印
took:1ms timeout:false total:1 hits MaxScore:1.0 hits========>> {"name":"lisi","age":"30","sex":"女"} <<========
8.2、分页查询
/***
* 条件查询
* @throws IOException
*/
@Test
public void queryByPagetest() throws IOException {
// 创建搜索请求对象
SearchRequest request = new SearchRequest();
request.indices("user");
// 构建查询的请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 分页查询
// 当前页其实索引(第一条数据的顺序号), from
sourceBuilder.from(0);
// 每页显示多少条 size
sourceBuilder.size(2);
request.source(sourceBuilder);
SearchResponse response = restHighLevelClient.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("<<========");
}
后台打印
took:1ms
timeout:false
total:6 hits
MaxScore:1.0
hits========>>
{"name":"zhangsan","age":"10","sex":"女"}
{"name":"lisi","age":"30","sex":"女"}
<<========
8.3、查询排序
/*** * 条件查询 * @throws IOException */ @Test public void queryByOrdertest() throws IOException { // 创建搜索请求对象 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 = restHighLevelClient.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("<<========"); }
后台打印
took:1ms timeout:false total:6 hits MaxScore:NaN hits========>> {"name":"zhangsan","age":"10","sex":"女"} {"name":"wangwu2","age":"20","sex":"女"} {"name":"wangwu4","age":"20","sex":"男"} {"name":"lisi","age":"30","sex":"女"} {"name":"wangwu1","age":"40","sex":"男"} {"name":"wangwu3","age":"50","sex":"男"} <<========
9、高级查询-组合查询 & 范围查询
9.1、组合查询
/*** * 条件查询 * @throws IOException */ @Test public void queryByCombinattest() throws IOException { // 创建搜索请求对象 SearchRequest request = new SearchRequest(); request.indices("user"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); // 必须包含 boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30")); // 一定不含 boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan")); // 可能包含 boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男")); sourceBuilder.query(boolQueryBuilder); request.source(sourceBuilder); SearchResponse response = restHighLevelClient.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("<<========"); }
后台打印
took:28ms timeout:false total:1 hits MaxScore:1.0 hits========>> {"name":"lisi","age":"30","sex":"女"} <<======== Process finished with exit code 0
9.2、范围查询
import com.lun.elasticsearch.hello.ConnectElasticsearch; import com.lun.elasticsearch.hello.ElasticsearchTask; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; public class QueryDoc { public static final ElasticsearchTask SEARCH_BY_RANGE = client -> { // 创建搜索请求对象 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("<<========"); }; public static void main(String[] args) { ConnectElasticsearch.connect(SEARCH_BY_RANGE); } }
后台打印
took:1ms timeout:false total:5 hits MaxScore:1.0 hits========>> {"name":"zhangsan","age":"10","sex":"女"} {"name":"lisi","age":"30","sex":"女"} {"name":"wangwu1","age":"40","sex":"男"} {"name":"wangwu2","age":"20","sex":"女"} {"name":"wangwu4","age":"20","sex":"男"} <<======== Process finished with exit code 0
10、高级查询-模糊查询 & 高亮查询
10.1、模糊查询
import com.lun.elasticsearch.hello.ConnectElasticsearch; import com.lun.elasticsearch.hello.ElasticsearchTask; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; 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.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; public class QueryDoc { public static final ElasticsearchTask SEARCH_BY_FUZZY_CONDITION = client -> { // 创建搜索请求对象 SearchRequest request = new SearchRequest(); request.indices("user"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.fuzzyQuery("name","wangwu").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("<<========"); }; public static void main(String[] args) { // ConnectElasticsearch.connect(SEARCH_ALL); // ConnectElasticsearch.connect(SEARCH_BY_CONDITION); // ConnectElasticsearch.connect(SEARCH_BY_PAGING); // ConnectElasticsearch.connect(SEARCH_WITH_ORDER); // ConnectElasticsearch.connect(SEARCH_BY_BOOL_CONDITION); // ConnectElasticsearch.connect(SEARCH_BY_RANGE); ConnectElasticsearch.connect(SEARCH_BY_FUZZY_CONDITION); } }
后台打印
took:152ms timeout:false total:4 hits MaxScore:1.2837042 hits========>> {"name":"wangwu1","age":"40","sex":"男"} {"name":"wangwu2","age":"20","sex":"女"} {"name":"wangwu3","age":"50","sex":"男"} {"name":"wangwu4","age":"20","sex":"男"} <<======== Process finished with exit code 0
10.2、高亮查询
import com.lun.elasticsearch.hello.ConnectElasticsearch; import com.lun.elasticsearch.hello.ElasticsearchTask; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; 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.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import java.util.Map; public class QueryDoc { public static final ElasticsearchTask SEARCH_WITH_HIGHLIGHT = client -> { // 高亮查询 SearchRequest request = new SearchRequest().indices("user"); //2.创建查询请求体构建器 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构建查询方式:高亮查询 TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","zhangsan"); //设置查询方式 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("<<::::"); }; public static void main(String[] args) { ConnectElasticsearch.connect(SEARCH_WITH_HIGHLIGHT); } }
后台打印
took::672ms time_out::false total::1 hits max_score::1.0 hits::::>> {"name":"zhangsan","age":"10","sex":"女"} {name=[name], fragments[[<font color='red'>zhangsan</font>]]} <<:::: Process finished with exit code 0
11、高级查询-最大值查询 & 分组查询
1、最大值查询
import com.lun.elasticsearch.hello.ConnectElasticsearch; import com.lun.elasticsearch.hello.ElasticsearchTask; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; 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.AggregationBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import java.util.Map; public class QueryDoc { public static final ElasticsearchTask SEARCH_WITH_MAX = client -> { // 高亮查询 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); }; public static void main(String[] args) { ConnectElasticsearch.connect(SEARCH_WITH_MAX); } }
后台打印
{"took":16,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":6,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"user","_type":"_doc","_id":"1001","_score":1.0,"_source":{"name":"zhangsan","age":"10","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1002","_score":1.0,"_source":{"name":"lisi","age":"30","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1003","_score":1.0,"_source":{"name":"wangwu1","age":"40","sex":"男"}},{"_index":"user","_type":"_doc","_id":"1004","_score":1.0,"_source":{"name":"wangwu2","age":"20","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1005","_score":1.0,"_source":{"name":"wangwu3","age":"50","sex":"男"}},{"_index":"user","_type":"_doc","_id":"1006","_score":1.0,"_source":{"name":"wangwu4","age":"20","sex":"男"}}]},"aggregations":{"max#maxAge":{"value":50.0}}} Process finished with exit code 0
分组查询
import com.lun.elasticsearch.hello.ConnectElasticsearch; import com.lun.elasticsearch.hello.ElasticsearchTask; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; 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.AggregationBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import java.util.Map; public class QueryDoc { public static final ElasticsearchTask SEARCH_WITH_GROUP = client -> { 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); }; public static void main(String[] args) { ConnectElasticsearch.connect(SEARCH_WITH_GROUP); } }
后台打印
{"took":10,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":6,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"user","_type":"_doc","_id":"1001","_score":1.0,"_source":{"name":"zhangsan","age":"10","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1002","_score":1.0,"_source":{"name":"lisi","age":"30","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1003","_score":1.0,"_source":{"name":"wangwu1","age":"40","sex":"男"}},{"_index":"user","_type":"_doc","_id":"1004","_score":1.0,"_source":{"name":"wangwu2","age":"20","sex":"女"}},{"_index":"user","_type":"_doc","_id":"1005","_score":1.0,"_source":{"name":"wangwu3","age":"50","sex":"男"}},{"_index":"user","_type":"_doc","_id":"1006","_score":1.0,"_source":{"name":"wangwu4","age":"20","sex":"男"}}]},"aggregations":{"lterms#age_groupby":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[{"key":20,"doc_count":2},{"key":10,"doc_count":1},{"key":30,"doc_count":1},{"key":40,"doc_count":1},{"key":50,"doc_count":1}]}}} Process finished with exit code 0
以上是关于Elasticsearch之JAVA API操作的主要内容,如果未能解决你的问题,请参考以下文章
[ElasticSearch]Java API 之 索引管理