赞
踩
老早之前写过一篇SpringBoot操作ElasticSearch的文章,但是内容过于简单,只是简单交代了下,为了更好的学习ElasticSearch这个搜索引擎,那么在更一篇贴,本文中使用的ElasticSearch为7.4.2,注意哦!那么elasticsearch-rest-high-level-client使用的也是同样的版本!这篇文章可以理解为是SpringBoot整合Elasticsearch的续集,可以先照着上文先把之前的代码准备下!
创建索引
@Test
void createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("user");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
log.info("索引操作===>"+acknowledged);
}
查询索引
@Test
void selectIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("user");
GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
Map<String, List<AliasMetaData>> aliases = getIndexResponse.getAliases();
Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
Map<String, Settings> settings = getIndexResponse.getSettings();
log.info("aliases===>{}",aliases);
log.info("mappings===>{}",mappings);
log.info("settings===>{}",settings);
}
这里返回的东西和Kibana操作返回的时一样的,只不过在java中封装成了对象
删除索引
@Test
void deleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("user");
AcknowledgedResponse acknowledgedResponse = client.indices().delete(request, RequestOptions.DEFAULT);
log.info("索引操作===>{}",acknowledgedResponse.isAcknowledged());
}
新增数据
@Test
void insertDoc() throws IOException {
IndexRequest request = new IndexRequest();
request.index("user").id("1");
User user = new User().setName("tao").setAge(18).setSex('男');
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
request.source(userJson, XContentType.JSON);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
log.info("Result===>{}",indexResponse.getResult());
}
或者
@Test
void insertDoc2() throws IOException{
IndexRequest indexRequest = new IndexRequest("user");
indexRequest.id("1");
indexRequest.source("userName", "tao", "age", 18, "sex", "M");
IndexResponse index = client.index((indexRequest), MallElasticSearchConfig.COMMON_OPTIONS);
log.info("===>", index.getResult());
}
查询数据
@Test
void selectDoc() throws IOException{
GetRequest request = new GetRequest();
request.index("user").id("1");
GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
log.info("===>{}",documentFields.getSourceAsString());
}
删除数据
@Test
void deleteDoc() throws IOException{
DeleteRequest request = new DeleteRequest();
request.index("user").id("1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
log.info("===>{}",response.toString());
}
批量添加数据
@Test
void bulkInsertDoc() throws IOException{
BulkRequest request = new BulkRequest();
ObjectMapper mapper = new ObjectMapper();
User user1 = new User().setName("tao").setAge(18).setSex('男');
User user2 = new User().setName("yyy").setAge(17).setSex('女');
User user3 = new User().setName("dry").setAge(16).setSex('女');
request.add(new IndexRequest().index("user").id("1").source(mapper.writeValueAsString(user1),XContentType.JSON));
request.add(new IndexRequest().index("user").id("2").source(mapper.writeValueAsString(user2),XContentType.JSON));
request.add(new IndexRequest().index("user").id("3").source(mapper.writeValueAsString(user3),XContentType.JSON ));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
log.info("Took===>{}",response.getTook());
log.info("Items===>{}",response.getItems());
}
批量删除数据
@Test
void bulkDeleteDoc() throws IOException{
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1"));
request.add(new DeleteRequest().index("user").id("2"));
request.add(new DeleteRequest().index("user").id("3"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
log.info("Took===>{}",response.getTook());
log.info("Items===>{}",response.getItems());
}
查询全部
/**
* {
* "query": {
* "match_all": {}
* }
* }
* @throws IOException
*/
@Test
void searchDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
条件查询
/**
* {
* "query": {
* "term": {
* "age": {
* "value": "18"
* }
* }
* }
* }
* @throws IOException
*/
@Test
void searchQueryDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",18)));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
分页查询
/**
* {
* "query": {
* "match_all": {}
* },
* "from": 0,
* "size": 2
* }
* @throws IOException
*/
@Test
void searchPageDoc() throws IOException{
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 = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
查询排序
/**
* {
* "query": {
* "match_all": {}
* },
* "sort": [
* {
* "age": {
* "order": "asc"
* }
* }
* ]
* }
* @throws IOException
*/
@Test
void searchOrderDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.sort("age", SortOrder.ASC);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
查询指定字段
/**
* {
* "query": {
* "match_all": {}
* },
* "sort": [
* {
* "age": {
* "order": "asc"
* }
* }
* ],
* "_source": {
* "includes": [],
* "excludes":["sex"]
* }
* }
* @throws IOException
*/
@Test
void searchSourceDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
builder.sort("age", SortOrder.ASC);
String[] excludes = {"sex"};
String[] includes = {};
builder.fetchSource(includes, excludes);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
组合查询
/**
* {
* "query": {
* "bool": {
* "must": [
* {
* "match": {
* "age": 18
* }
* }
* ],
* "must_not": [
* {
* "match": {
* "sex": "女"
* }
* }
* ]
* }
* }
* }
* @throws IOException
*/
@Test
void searchBoolDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.matchQuery("age", 18));
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "女"));
builder.query(boolQueryBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
范围查询
/**
* {
* "query": {
* "range": {
* "age": {
* "gte": 20,
* "lte": 22
* }
* }
* }
* }
* @throws IOException
*/
@Test
void searchRangeDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
rangeQuery.gte(20);
rangeQuery.lte(22);
builder.query(rangeQuery);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
模糊查询
@Test
void searchFuzzyDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.fuzzyQuery("name", "毛金").fuzziness(Fuzziness.ONE));
//.fuzziness(Fuzziness.ONE)匹配多少个
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h.getSourceAsString());
});
}
高亮查询
/**
* {
* "query": {
* "terms": {
* "name": [
* "金"
* ]
* }
* },
* "highlight": {
* "fields": {
* "name": {
* "pre_tags": [
* "<font color='red'>"
* ],
* "post_tags": [
* "</font>"
* ]
* }
* }
* }
* }
* @throws IOException
*/
@Test
void searchHighlighterDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermsQueryBuilder termQueryBuilder = QueryBuilders.termsQuery("name", "金");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");
highlightBuilder.postTags("</font>");
highlightBuilder.field("name");
builder.highlighter(highlightBuilder);
builder.query(termQueryBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
hits.forEach(h ->{
log.info("===>"+h);
});
}
聚合查询
/**
* {
* "aggs": {
* "ageMax": {
* "max": {
* "field": "age"
* }
* }
* }
* }
* @throws IOException
*/
@Test
void searchAggregationDoc() throws IOException{
SearchRequest request = new SearchRequest();
request.indices("user");
SearchSourceBuilder builder = new SearchSourceBuilder();
MaxAggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
builder.aggregation(aggregationBuilder);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
log.info("Aggregations===>"+response.getAggregations());
}
聚合查询-分组
/**
* {
* "aggs": {
* "age_group": {
* "terms": {
* "field": "age"
* }
* }
* }
* }
* @throws IOException
*/
@Test
void searchAggregationGroupDoc() throws IOException{
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 = client.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
log.info("TotalHits===>{}",hits.getTotalHits());
log.info("Took===>{}",response.getTook());
log.info("Aggregations===>"+response.getAggregations());
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。