ElasticSearch教程入门到精通——第二部分(基于ELK技术栈elasticsearch 7.x新特性)

ElasticSearch教程入门到精通——第二部分(基于ELK技术栈elasticsearch 7.x新特性)

  • 1. JavaAPI-环境准备
    • 1.1 新建Maven工程——添加依赖
    • 1.2 HelloElasticsearch
  • 2. 索引
    • 2.1 索引——创建
    • 2.2 索引——查询
    • 2.3 索引——删除
  • 3. 文档
    • 3.1 文档——重构
    • 3.2 文档——新增
    • 3.3 文档——修改
    • 3.4 文档——简单操作
      • 3.4.1 文档——简单查询
      • 3.4.2 文档——简单删除
    • 3.5 文档——批量操作
      • 3.5.1 文档——批量新增
      • 3.5.2 文档——批量删除
    • 3.6 文档——高级查询
      • 3.6.1 文档——高级查询——全量查询
      • 3.6.2 文档——高级查询——条件查询
      • 3.6.3 文档——高级查询——分页查询
      • 3.6.4 文档——高级查询——查询排序
      • 3.6.5 文档——高级查询——组合查询
      • 3.6.6 文档——高级查询——范围查询
      • 3.6.7 文档——高级查询——模糊查询
      • 3.6.9 文档——高级查询——高亮查询
      • 3.6.10 文档——高级查询——最大值查询
      • 3.6.11 文档——高级查询——分组查询

在这里插入图片描述

在这里插入图片描述

1. JavaAPI-环境准备

1.1 新建Maven工程——添加依赖

<dependencies><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>
</dependencies>

1.2 HelloElasticsearch

import java.io.IOException;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;public class HelloElasticsearch {public static void main(String[] args) throws IOException {// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
//		...System.out.println(client);// 关闭客户端连接client.close();}
}

在这里插入图片描述

2. 索引

2.1 索引——创建

在这里插入图片描述

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 ESTest_Index_Create {public static void main(String[] args) throws IOException {RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));// 创建索引CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);boolean acknowledged = createIndexResponse.isAcknowledged();System.out.println("acknowledged = " + acknowledged);restHighLevelClient.close();}
}

后台打印:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2.2 索引——查询

package com.atguigu.es.test;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.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;import java.io.IOException;
import java.util.List;
import java.util.Map;public class ESTest_Index_Search {public static void main(String[] args) throws IOException {RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));// 查询索引GetIndexRequest getIndexRequest = new GetIndexRequest("user");GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);Map<String, List<AliasMetadata>> aliases = getIndexResponse.getAliases();System.out.println("aliases = " + aliases);Map<String, MappingMetadata> mappings = getIndexResponse.getMappings();System.out.println("mappings = " + mappings);Map<String, Settings> settings = getIndexResponse.getSettings();System.out.println("settings = " + settings);restHighLevelClient.close();}
}

后台打印:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2.3 索引——删除

package com.atguigu.es.test;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.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;import java.io.IOException;
import java.util.List;
import java.util.Map;public class ESTest_Index_Delete {public static void main(String[] args) throws IOException {RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));// 删除索引DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);boolean acknowledged = delete.isAcknowledged();System.out.println("acknowledged = " + acknowledged);restHighLevelClient.close();}
}

后台打印:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

3. 文档

3.1 文档——重构

上文由于频繁使用以下连接Elasticsearch和关闭它的代码,于是个人对它进行重构。

public class SomeClass {public static void main(String[] args) throws IOException {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));...client.close();}
}

重构后的代码:

import org.elasticsearch.client.RestHighLevelClient;public interface ElasticsearchTask {void doSomething(RestHighLevelClient client) throws Exception;}
public class ConnectElasticsearch{public static void connect(ElasticsearchTask task){// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));try {task.doSomething(client);// 关闭客户端连接client.close();} catch (Exception e) {e.printStackTrace();}}
}

接下来,如果想让Elasticsearch完成一些操作,就编写一个lambda式即可。

public class SomeClass {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//do something});}
}

在这里插入图片描述

3.2 文档——新增

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lun.elasticsearch.hello.ConnectElasticsearch;
import com.lun.elasticsearch.model.User;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;public class InsertDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {// 新增文档 - 请求对象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 = client.index(request, RequestOptions.DEFAULT);3.打印结果信息System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());});}
}

后台打印:

在这里插入图片描述

在这里插入图片描述

3.3 文档——修改

import com.lun.elasticsearch.hello.ConnectElasticsearch;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;public class UpdateDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {// 修改文档 - 请求对象UpdateRequest request = new UpdateRequest();// 配置修改参数request.index("user").id("1001");// 设置请求体,对数据进行修改request.doc(XContentType.JSON, "sex", "女");// 客户端发送请求,获取响应对象UpdateResponse response = client.update(request, RequestOptions.DEFAULT);System.out.println("_index:" + response.getIndex());System.out.println("_id:" + response.getId());System.out.println("_result:" + response.getResult());});}}

后台打印:

_index:user
_id:1001
_result:UPDATEDProcess finished with exit code 0

在这里插入图片描述

3.4 文档——简单操作

3.4.1 文档——简单查询

import com.lun.elasticsearch.hello.ConnectElasticsearch;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;public class GetDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//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());});}
}

后台打印:

_index:user
_type:_doc
_id:1001
source:{"name":"zhangsan","age":30,"sex":"男"}Process finished with exit code 0

3.4.2 文档——简单删除

import com.lun.elasticsearch.hello.ConnectElasticsearch;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;public class DeleteDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//创建请求对象DeleteRequest request = new DeleteRequest().index("user").id("1001");//客户端发送请求,获取响应对象DeleteResponse response = client.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

在这里插入图片描述

3.5 文档——批量操作

3.5.1 文档——批量新增

import com.lun.elasticsearch.hello.ConnectElasticsearch;
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.common.xcontent.XContentType;public class BatchInsertDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//创建批量新增请求对象BulkRequest request = new BulkRequest();request.add(newIndexRequest().index("user").id("1001").source(XContentType.JSON, "name","zhangsan"));request.add(newIndexRequest().index("user").id("1002").source(XContentType.JSON, "name","lisi"));request.add(newIndexRequest().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());});}
}

后台打印

took:294ms
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@2beee7ffProcess finished with exit code 0

在这里插入图片描述

3.5.2 文档——批量删除

import com.lun.elasticsearch.hello.ConnectElasticsearch;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;public class BatchDeleteDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//创建批量删除请求对象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());});}
}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6 文档——高级查询

3.6.1 文档——高级查询——全量查询

先批量增加数据

public class BatchInsertDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {//创建批量新增请求对象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 = client.bulk(request, RequestOptions.DEFAULT);//打印结果信息System.out.println("took:" + responses.getTook());System.out.println("items:" + responses.getItems());});}
}

后台打印

在这里插入图片描述

查询所有索引数据

import com.lun.elasticsearch.hello.ConnectElasticsearch;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;public class QueryDoc {public static void main(String[] args) {ConnectElasticsearch.connect(client -> {// 创建搜索请求对象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("<<========");});}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.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.QueryBuilders;
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_CONDITION = client -> {// 创建搜索请求对象SearchRequest request = new SearchRequest();request.indices("user");// 构建查询的请求体SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(QueryBuilders.termQuery("age", "30"));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_CONDITION);}
}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.3 文档——高级查询——分页查询

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.QueryBuilders;
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_PAGING = client -> {// 创建搜索请求对象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("<<========");};public static void main(String[] args) {ConnectElasticsearch.connect(SEARCH_BY_CONDITION);}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.4 文档——高级查询——查询排序

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.QueryBuilders;
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_WITH_ORDER = client -> {// 创建搜索请求对象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("<<========");};public static void main(String[] args) {ConnectElasticsearch.connect(SEARCH_WITH_ORDER);}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.5 文档——高级查询——组合查询

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.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_BOOL_CONDITION = client -> {// 创建搜索请求对象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 = 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_BOOL_CONDITION);}
}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.6 文档——高级查询——范围查询

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("20");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);}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.7 文档——高级查询——模糊查询

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);}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.9 文档——高级查询——高亮查询

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);}}

后台打印

在这里插入图片描述

在这里插入图片描述

3.6.10 文档——高级查询——最大值查询

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);}}

后台打印

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3.6.11 文档——高级查询——分组查询

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);}}

后台打印

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/830834.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SQL 基础 | BETWEEN 的常见用法

在SQL中&#xff0c;BETWEEN是一个操作符&#xff0c;用于选取介于两个值之间的数据。 它包含这两个边界值。BETWEEN操作符常用于WHERE子句中&#xff0c;以便选取某个范围内的值。 以下是BETWEEN的一些常见用法&#xff1a; 选取介于两个值之间的值&#xff1a; 使用 BETWEEN来…

基于昇腾AI | 英码科技EA500I使用AscendCL实现垃圾分类和视频物体分类应用

现如今&#xff0c;人工智能迅猛发展&#xff0c;AI赋能产业发展的速度正在加快&#xff0c;“AI”的需求蜂拥而来&#xff0c;但AI应用快速落地的过程中仍存在很大的挑战&#xff1a;向下需要适配的硬件&#xff0c;向上需要完善的技术支持&#xff0c;两者缺一不可。 基于此&…

【配置】Docker搭建JSON在线解析网站

云服务器打开端口8787 连接上docker运行 docker run -id --name jsonhero -p 8787:8787 -e SESSION_SECRETabc123 henryclw/jsonhero-webhttp://ip:8787访问 Github&#xff1a;地址

STM32 看门狗WDG

一、看门狗&#xff08;Watchdog&#xff09; 看门狗可以监控程序的运行状态&#xff0c;当程序因为设计漏洞、硬件故障、电磁干扰等原因&#xff0c;出现卡死或跑飞现象时&#xff0c;看门狗能及时复位程序&#xff0c;避免程序陷入长时间的罢工状态&#xff0c;保证系统的可靠…

Django后台项目开发实战一

开发环境使用 Anaconda, IDE 使用 pycharm 第一阶段 创建 Django 项目 在 Anaconda Prompt 中逐步输入下面的命令&#xff08;之后的所有命令都在这个&#xff09; 首先创建一个虚拟环境&#xff0c;名称自拟&#xff0c;python 版本我这里使用 3.9.18 关于 python 版本和…

PotatoPie 4.0 实验教程(28) —— FPGA实现sobel算子对摄像头图像进行边缘提取

什么是sobel算子&#xff1f; Sobel 算子是一种常用的边缘检测算子&#xff0c;用于在图像中检测边缘。它基于对图像进行梯度运算&#xff0c;可以帮助识别图像中灰度值变化较大的区域&#xff0c;从而找到图像中的边缘。 Sobel 算子通过计算图像的水平和垂直方向的一阶导数来…

Linux 虚拟主机切换php版本及参数

我使用的Hostease的Linux虚拟主机产品,由于网站程序需要支持高版本的PHP,程序已经上传到主机&#xff0c;但是没有找到切换PHP以及查看PHP有哪些版本的位置&#xff0c;因此咨询了Hostease的技术支持&#xff0c;寻求帮助了解到可以实现在cPanel面板上找到此切换PHP版本的按钮&…

2024 五一杯高校数学建模邀请赛(A题)|钢板最优切割路径问题|建模秘籍文章代码思路大全

铛铛&#xff01;小秘籍来咯&#xff01; 小秘籍团队独辟蹊径&#xff0c;运用Dijkstra算法&#xff0c;最优路径切割等强大工具&#xff0c;构建了这一题的详细解答哦&#xff01; 为大家量身打造创新解决方案。小秘籍团队&#xff0c;始终引领着建模问题求解的风潮。 抓紧小秘…

Stability AI 推出稳定音频 2.0:为创作者提供先进的 AI 生成音频

概述 Stability AI 的发布再次突破了创新的界限。这一尖端模型以其前身的成功为基础&#xff0c;引入了一系列突破性的功能&#xff0c;有望彻底改变艺术家和音乐家创建和操作音频内容的方式。 Stable Audio 2.0 代表了人工智能生成音频发展的一个重要里程碑&#xff0c;为质量…

Flask模版详解

Flask模版详解 概述Jinja2模板引擎渲染模版的步骤变量控制结构自定义错误页面链接静态文件 概述 模板是一个包含响应文本的文件&#xff0c;其中包含用占位变量表示的动态部分&#xff0c;其具体值只在请求的上下文中才能知道。使用真实值替换变量&#xff0c;再返回最终得到的…

Android4.4真机移植过程笔记(一)

1、RK源码编译 获取内核源码&#xff1a; git clone git172.28.1.172:rk3188_kernel -b xtc_ok1000 内核编译环境&#xff1a; 从172.28.1.132编译服务器的/data1/ZouZhiPing目录下拷贝toolchain.tar.gz&#xff08;交叉编译工具链&#xff09;并解压到与rk3188_kernel同级目…

Golang | Leetcode Golang题解之第59题螺旋矩阵II

题目&#xff1a; 题解&#xff1a; func generateMatrix(n int) [][]int {matrix : make([][]int, n)for i : range matrix {matrix[i] make([]int, n)}num : 1left, right, top, bottom : 0, n-1, 0, n-1for left < right && top < bottom {for column : lef…

前端发起网络请求的几种常见方式(XMLHttpRequest、FetchApi、jQueryAjax、Axios)

摘要 前端发起网络请求的几种常见方式包括&#xff1a; XMLHttpRequest (XHR)&#xff1a; 这是最传统和最常见的方式之一。它允许客户端与服务器进行异步通信。XHR API 提供了一个在后台发送 HTTP 请求和接收响应的机制&#xff0c;使得页面能够在不刷新的情况下更新部分内容…

【分享】如何将word格式文档转化为PDF格式

在日常的办公和学习中&#xff0c;我们经常需要将Word文档转换为PDF格式。PDF作为一种通用的文件格式&#xff0c;具有跨平台、易读性高等优点&#xff0c;因此在许多场合下都更为适用。那么&#xff0c;如何实现Word转PDF呢&#xff1f;本文将介绍几种常用的方法&#xff0c;帮…

光伏储能是什么意思?有什么好处?

随着全球能源需求的持续增长和对环保要求的不断提高&#xff0c;新能源技术的发展已成为全球的热门话题。光伏储能作为其中的一项重要技术&#xff0c;正在逐渐受到人们的关注。那么&#xff0c;光伏储能是什么意思&#xff1f;它又有哪些好处呢&#xff1f; 一、光伏储能的定义…

『FPGA通信接口』DDR(3)DDR3颗粒读写测试

文章目录 前言1.配套工程简介2.测试内容与策略3. 测试程序分析4.程序结果分析5.一个IP控制两颗DDR36.传送门 前言 以四颗MT41K512M16HA-125AIT颗粒为例&#xff0c;介绍如何在一块新制板卡上做关于DDR3的器件测试。前面两篇介绍了什么是DDR&#xff0c;并介绍了xilinx给出的FPG…

神经网络反向传播算法

今天我们来看一下神经网络中的反向传播算法&#xff0c;之前介绍了梯度下降与正向传播~ 神经网络的反向传播 专栏&#xff1a;&#x1f48e;实战PyTorch&#x1f48e; 反向传播算法&#xff08;Back Propagation&#xff0c;简称BP&#xff09;是一种用于训练神经网络的算…

品牌百度百科词条需要什么资料?

品牌百度百科词条是一个品牌的数字化名片&#xff0c;更是品牌历史、文化、实力的全面展现。 作为一个相当拿得出手的镀金名片&#xff0c;品牌百度百科词条创建需要什么资料&#xff0c;今天伯乐网络传媒就来给大家讲解一下。 一、品牌基本信息&#xff1a;品牌身份的明确 品…

【漏洞复现】科达 MTS转码服务器 任意文件读取漏洞

0x01 产品简介 科达 MTS转码服务器是一款专业的视频转码设备&#xff0c;采用了高性能的硬件配置和先进的转码技术&#xff0c;能够实现高效、高质量的视频转码。 0x02 漏洞概述 科达 MTS转码服务器存在任意文件读取漏洞&#xff0c;攻击可以通过该漏洞读取服务器任意敏感信…

FSD自动驾驶泛谈

特斯拉的FSD&#xff08;Full-Self Driving&#xff0c;全自动驾驶&#xff09;系统是特斯拉公司研发的一套完全自动驾驶系统。旨在最终实现车辆在多种驾驶环境下无需人类干预的自动驾驶能力。以下是对FSD系统的详细探讨&#xff1a; 系统概述 FSD是特斯拉的自动驾驶技术&…