Elasticsearch软件是由Java语言开发的,所以也可以通过JavaAPI的方式对Elasticearch服务进行访问。
首先在pom.xml中引入下述依赖:
org.elasticsearch elasticsearch 7.8.0
org.elasticsearch.client elasticsearch-rest-high-level-client 7.8.0
测试类创建下述测试方法:
package com.bc.work;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ElasticsearchTests {@Testpublic void helloElasticsearchTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));System.out.println(client);// 关闭客户端连接client.close();}
}
单元测试没有报错,则说明上述配置没有什么问题。
package com.bc.work;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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ElasticsearchTests {@Testpublic void createIndexTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建索引 - 请求对象CreateIndexRequest request = new CreateIndexRequest("user");// 发送请求,获取响应CreateIndexResponse response = client.indices().create(request,RequestOptions.DEFAULT);boolean acknowledged = response.isAcknowledged();// 响应状态System.out.println("操作状态 = " + acknowledged);// 关闭客户端连接client.close();}
}
执行上述测试代码,控制台输出:
操作状态 = true
package com.bc.work;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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ElasticsearchTests {@Testpublic void searchIndexTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 查询索引 - 请求对象GetIndexRequest request = new GetIndexRequest("user");// 发送请求,获取响应GetIndexResponse response = client.indices().get(request,RequestOptions.DEFAULT);System.out.println("aliases:"+response.getAliases());System.out.println("mappings:"+response.getMappings());System.out.println("settings:"+response.getSettings());client.close();}
}
执行上述测试代码,控制台输出:
aliases:{user=[]}
mappings:{user=org.elasticsearch.cluster.metadata.MappingMetadata@b15855d4}
settings:{user={"index.creation_date":"1669794091814","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user","index.routing.allocation.include._tier_preference":"data_content","index.uuid":"Zt1OBPSCQZGZ4VkMfJA2Yw","index.version.created":"8050199"}}
package com.bc.work;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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ElasticsearchTests {@Testpublic void deleteIndexTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 删除索引 - 请求对象DeleteIndexRequest request = new DeleteIndexRequest("user");// 发送请求,获取响应AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);// 操作结果System.out.println("操作结果 : " + response.isAcknowledged());client.close();}
}
执行上述测试代码,控制台输出:
操作结果 : true
package com.bc.work;import cn.hutool.json.JSONUtil;
import com.bc.work.dto.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ElasticsearchTests {@Testpublic void insertDocTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 新增文档 - 请求对象IndexRequest request = new IndexRequest();// 设置索引及唯一性标识request.index("user").id("1001");// 创建数据对象User user = new User();user.setName("zhangsan");user.setAge(30);user.setSex("男");// 添加文档数据,数据格式为 JSON 格式String userJson = JSONUtil.toJsonStr(user);request.source(userJson, XContentType.JSON);try{// 客户端发送请求,获取响应对象client.index(request, RequestOptions.DEFAULT);}catch (Exception e){System.out.println(e.getMessage());if(e.getMessage().contains("Unable to parse response body for Response{requestLine=")&&e.getMessage().contains("response=HTTP/1.1 200 OK")){System.out.println("新增文档数据成功!!!");}else {System.out.println("新增文档数据失败!!!");}}client.close();}
}
执行上述测试代码,控制台输出:
Unable to parse response body for Response{requestLine=PUT /user/_doc/1001?timeout=1m HTTP/1.1, host=http://192.168.1.108:9200, response=HTTP/1.1 201 Created}
新增文档数据成功!!!
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ElasticsearchTests {@Testpublic void updateDocTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 修改文档 - 请求对象UpdateRequest request = new UpdateRequest();request.index("user").id("1001");// 设置请求体,对数据进行修改request.doc(XContentType.JSON,"sex","女");try{// 客户端发送请求,获取响应对象UpdateResponse response =client.update(request,RequestOptions.DEFAULT);}catch (Exception e){System.out.println(e.getMessage());if(e.getMessage().contains("Unable to parse response body for Response{requestLine=")&&e.getMessage().contains("response=HTTP/1.1 200 OK")){System.out.println("更新文档数据成功!!!");}else {System.out.println("更新文档数据失败!!!");}}client.close();}
}
执行上述测试代码,控制台输出:
Unable to parse response body for Response{requestLine=POST /user/_update/1001?timeout=1m HTTP/1.1, host=http://192.168.1.108:9200, response=HTTP/1.1 200 OK}
更新文档数据成功!!!
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ElasticsearchTests {@Testpublic void queryDocTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 1.创建请求对象GetRequest request = new GetRequest().index("user").id("1001");// 2.客户端发送请求,获取响应对象GetResponse response = client.get(request, RequestOptions.DEFAULT);// 3.打印结果信息System.out.println("_index:" + response.getIndex());System.out.println("_type:" + response.getType());System.out.println("_id:" + response.getId());System.out.println("source:" + response.getSourceAsString());client.close();}
}
执行上述测试代码,控制台输出:
_index:user
_type:null
_id:1001
source:{"sex":"女","name":"zhangsan","age":30}
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ElasticsearchTests {@Testpublic void deleteDocTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));//创建请求对象DeleteRequest request = new DeleteRequest().index("user").id("1001");try{//客户端发送请求,获取响应对象DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);}catch (Exception e){System.out.println(e.getMessage());if(e.getMessage().contains("Unable to parse response body for Response{requestLine=DELETE")&&e.getMessage().contains("response=HTTP/1.1 200 OK")){System.out.println("删除文档数据成功!!!");}else {System.out.println("删除文档数据失败!!!");}}client.close();}
}
执行上述测试代码,控制台输出:
Unable to parse response body for Response{requestLine=DELETE /user/_doc/1001?timeout=1m HTTP/1.1, host=http://192.168.1.108:9200, response=HTTP/1.1 200 OK}
删除文档数据成功!!!
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class BatchInsertTests {@Testpublic void batchInsertTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));//创建批量新增请求对象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 = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());client.close();}
}
执行上述测试代码,控制台输出:
took:294ms
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@2beee7ff
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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 org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class BatchDeleteTests {@Testpublic void batchInsertTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));//创建批量删除请求对象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 = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());client.close();}
}
执行上述测试代码,控制台输出:
took:108ms
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@7b02881e
往user索引中批量插入4条文档数据:
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "徐凤年","age",28,"sex","男"));
request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "姜泥","age",22,"sex","女"));
request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "南宫仆射","age",24,"sex","女"));
request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "青鸟","age",26,"sex","女"));
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class AllQueryTests {@Testpublic void allQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:1ms
timeout:false
total:4 hits
MaxScore:1.0
hits========>>
{"name":"徐凤年","age":28,"sex":"男"}
{"name":"姜泥","age":22,"sex":"女"}
{"name":"南宫仆射","age":24,"sex":"女"}
{"name":"青鸟","age":26,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ConditionQueryTests {@Testpublic void conditionQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.termQuery("sex", "女"));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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:3ms
timeout:false
total:3 hits
MaxScore:0.35667494
hits========>>
{"name":"姜泥","age":22,"sex":"女"}
{"name":"南宫仆射","age":24,"sex":"女"}
{"name":"青鸟","age":26,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class PageQueryTests {@Testpublic void pageQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.matchAllQuery());// 分页查询// 当前页其实索引(第一条数据的顺序号), fromsourceBuilder.from(0);// 每页显示多少条 sizesourceBuilder.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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:2ms
timeout:false
total:4 hits
MaxScore:1.0
hits========>>
{"name":"徐凤年","age":28,"sex":"男"}
{"name":"姜泥","age":22,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class SortQueryTests {@Testpublic void sortQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:47ms
timeout:false
total:4 hits
MaxScore:NaN
hits========>>
{"name":"姜泥","age":22,"sex":"女"}
{"name":"南宫仆射","age":24,"sex":"女"}
{"name":"青鸟","age":26,"sex":"女"}
{"name":"徐凤年","age":28,"sex":"男"}
<<========
package com.bc.work;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.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;public class CombinationQueryTests {@Testpublic void combinationQueryTest() throws Exception {// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();// 必须包含boolQueryBuilder.must(QueryBuilders.matchQuery("age", "24"));// 一定不含boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "姜泥"));// 可能包含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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:12ms
timeout:false
total:1 hits
MaxScore:1.3566749
hits========>>
{"name":"南宫仆射","age":24,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.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.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class ScopeQueryTests {@Testpublic void scopeQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");// 大于等于//rangeQuery.gte("30");// 小于等于rangeQuery.lte("22");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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:3ms
timeout:false
total:1 hits
MaxScore:1.0
hits========>>
{"name":"姜泥","age":22,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class FuzzyQueryTests {@Testpublic void fuzzyQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.fuzzyQuery("name","青鸟").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("<<========");client.close();}
}
执行上述测试代码,控制台输出:
took:13ms
timeout:false
total:1 hits
MaxScore:0.0
hits========>>
{"name":"青鸟","age":26,"sex":"女"}
<<========
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.index.query.QueryBuilders;
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.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.Map;@Slf4j
@SpringBootTest
public class HighLightQueryTests {@Testpublic void highLightQueryTest() throws Exception{// 1.创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 9200, "http")));SearchRequest request = new SearchRequest();request.indices("user");// 2.创建查询请求体构建器SearchSourceBuilder builder = new SearchSourceBuilder();TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("sex", "女");// 5.构建高亮字段HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("");//设置标签前缀highlightBuilder.postTags("");//设置标签后缀highlightBuilder.field("name");//设置高亮字段// 6.设置高亮构建对象builder.highlighter(highlightBuilder);// 4.设置查询方式builder.query(termsQueryBuilder);// 7.设置请求体request.source(builder);// 8.客户端发送请求,获取响应对象SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 9.打印响应结果SearchHits hits = response.getHits();System.out.println("took::"+response.getTook());System.out.println("total::"+hits.getTotalHits());for (SearchHit hit : hits) {System.out.println(hit.getSourceAsString());//打印高亮结果Map highlightFields = hit.getHighlightFields();System.out.println(highlightFields);}client.close();}
}
此处在接口返回中没有高亮部分,理论上这样写是没有问题的,我觉得这个可能版本的问题,升级一下或者更换一个依赖可能就好了,不过现在我是没有时间管这个问题。
PS:如果真的碰到了,那么就直接调用服务的原始API接口
最大值查询:
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class MaxValueQueryTests {@Testpublic void maxValueQueryTest() throws Exception {// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 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);client.close();}
}
执行上述测试代码,控制台输出:
{"took":23,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":4,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"user","_id":"1001","_score":1.0,"_source":{"name":"徐凤年","age":28,"sex":"男"}},{"_index":"user","_id":"1002","_score":1.0,"_source":{"name":"姜泥","age":22,"sex":"女"}},{"_index":"user","_id":"1003","_score":1.0,"_source":{"name":"南宫仆射","age":24,"sex":"女"}},{"_index":"user","_id":"1004","_score":1.0,"_source":{"name":"青鸟","age":26,"sex":"女"}}]},"aggregations":{"max#maxAge":{"value":28.0}}}
分组查询:
package com.bc.work;import lombok.extern.slf4j.Slf4j;
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.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@Slf4j
@SpringBootTest
public class GroupQueryTests {@Testpublic void groupQueryTest() throws Exception{// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.1.108", 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);client.close();}
}
执行上述测试代码,控制台输出:
{"took": 34,"timed_out": false,"_shards": {"total": 1,"successful": 1,"skipped": 0,"failed": 0},"hits": {"total": {"value": 4,"relation": "eq"},"max_score": 1.0,"hits": [{"_index": "user","_id": "1001","_score": 1.0,"_source": {"name": "徐凤年","age": 28,"sex": "男"}}, {"_index": "user","_id": "1002","_score": 1.0,"_source": {"name": "姜泥","age": 22,"sex": "女"}}, {"_index": "user","_id": "1003","_score": 1.0,"_source": {"name": "南宫仆射","age": 24,"sex": "女"}}, {"_index": "user","_id": "1004","_score": 1.0,"_source": {"name": "青鸟","age": 26,"sex": "女"}}]},"aggregations": {"lterms#age_groupby": {"doc_count_error_upper_bound": 0,"sum_other_doc_count": 0,"buckets": [{"key": 22,"doc_count": 1}, {"key": 24,"doc_count": 1}, {"key": 26,"doc_count": 1}, {"key": 28,"doc_count": 1}]}}
}