基于SringBoot2.2.2
导入依赖
创建配置类
package com.nkym.es.config;import org.apache.http.HttpHost;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestClientBuilder;import org.elasticsearch.client.RestHighLevelClient;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringBootConfiguration;import org.springframework.context.annotation.Bean;@SpringBootConfiguration //配置类public class ElasticSearchConfig { @Value("${es.host}") //Spring注解 从yml,properties文件中注入值 private String host; //ES主机域名 @Value("${es.port}") private int port;//ES端口号。默认9200. public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public ElasticSearchConfig(String host, int port) { this.host = host; this.port = port; } public ElasticSearchConfig() { } //创建RestHighLevelClient客户端,连接ES。 @Bean public RestHighLevelClient getRest(){ return new RestHighLevelClient(RestClient.builder(new HttpHost(this.host,this.port))); }}
前置工作做完了 我们开始测试。
创建测试类。
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient;}
索引API 创建索引隐式映射的Index
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { //连接ES的api 类似于jdbc @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test() throws IOException { //创建索引请求 //参数:索引名(必须小写) CreateIndexRequest indexRequest = new CreateIndexRequest("indexname"); CreateIndexResponse response = //在高级 REST 客户端中解析 REST 响应 参数1:创建索引的请求 参数2:固定值RequestOptions.DEFAULT restHighLevelClient.indices().create(indexRequest,RequestOptions.DEFAULT); //打印创建成功后的信息。 System.out.println(response.isAcknowledged()); System.out.println(response.isShardsAcknowledged()); }}
显式映射的Index
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test() throws IOException { CreateIndexRequest indexRequest = new CreateIndexRequest("indexname"); indexRequest.mapping( //定义映射 "{n" + " "properties": {n" + " "message": {n" + " "type": "text"n" + " }n" + " }n" + "}", XContentType.JSON); //这个映射以Json字符串形式提供 CreateIndexResponse response = restHighLevelClient.indices().create(indexRequest,RequestOptions.DEFAULT); System.out.println(response.isAcknowledged()); System.out.println(response.isShardsAcknowledged()); }}
删除索引@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test22() throws IOException { //创建删除索引请求 参数:要删除的索引名字 DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("indexname"); //调用高级Rest客户端响应请求。 AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); //打印响应结果。 System.out.println(delete.isAcknowledged()); }}
判断索引是否存在
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test22() throws IOException { //创建GETindex请求, 参数(可变形参可以填多个):要判断的索引名字 GetIndexRequest request = new GetIndexRequest("indexname","person"); //响应是一个boolean值,索引(或多个索引)是否存在。 boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT); //只有所有的index存在时才会返回ture有一个不存在都会返回false System.out.println(exists); }}
添加映射(类似于Mysql增加字段)@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test22() throws IOException { //创建增加Mapping请求 PutMappingRequest request = new PutMappingRequest("indexname"); request.source(//按照原生ES增加映射格式写 String语句 "{n" + " "properties": {n" + " "name": {n" + " "type": "text"n" + " }n" + " }n" + "}", XContentType.JSON); //Rest高级客户端响应请求,返回请求结果。 AcknowledgedResponse response = restHighLevelClient.indices().putMapping(request, RequestOptions.DEFAULT); System.out.println(response); }}
获取映射(类似MYSQL获取表结构)@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test22() throws IOException { //创建获取映射的请求 GetMappingsRequest request = new GetMappingsRequest();//获取那个索引的映射,若不设置默认获取所有索引的映射 request.indices("indexname");//rest高级客户端响应请求 GetMappingsResponse mapping = restHighLevelClient.indices().getMapping(request, RequestOptions.DEFAULT);//遍历响应结果的映射。 //如果上方request请求没有设置索引名,可以用这个语句获取指定索引的mapping, mapping.mappings().get(""); for (MappingmetaData value : mapping.mappings().values()) { System.out.println(value.getSourceAsMap()); } }}
执行上面操作返回结果和postMan响应结果一致。
获取某一字段的映射@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test22() throws IOException { //创建获取字段映射请求。 GetFieldMappingsRequest request = new GetFieldMappingsRequest(); //指定索引库名字 request.indices("indexname"); //指定字段名,可以有多个 request.fields("message"); //Rest客户端响应请求 GetFieldMappingsResponse mapping = restHighLevelClient.indices().getFieldMapping(request, RequestOptions.DEFAULT); //指定获取字段映射。 System.out.println(mapping.mappings().get("indexname").get("field").sourceAsMap()); }
文档API 创建文档@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; //方式一:Map方式 @Test public void test() throws IOException { //创建索引请求 IndexRequest request = new IndexRequest("indexname"); //创建Map数据源,在Map中放入要存入文档中的数据 Map
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void test() throws IOException { //创建获取文档请求 参数1:索引名字,参数2:文档ID GetRequest request = new GetRequest("indexname","1"); //Rest客户端响应 GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT); //以String形式检索文档 System.out.println(response.getSourceAsString());//以字节形式检索文档byte[] System.out.println(new String(response.getSourceAsBytes())); //将文档检索为Map
执行结果
判断文档是否存在@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient;//判断单个文档 @Test public void test() throws IOException { //创建获取请求 GetRequest request = new GetRequest("indexname","1"); //Rest客户端响应请求返回Boolean,有为true,没有为false boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT); System.out.println(exists); } //判断多个文档 @Test public void test() throws IOException { GetRequest request = new GetRequest(); request.id("1").id("1").index("indexname"); boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT); System.out.println("exists = " + exists); }}
删除文档@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建删除请求 DeleteRequest request = new DeleteRequest("indexname","2"); //Rest客户端响应请求 DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT); } }
修改文档@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建更新请求 UpdateRequest request = new UpdateRequest(); //创建Map 放入数据 Map
相当于把多个文档操作放入批量操作API中。
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建批处理请求 BulkRequest request = new BulkRequest(); //创建放入的数据 Map
SearchRequest 用于与搜索文档、聚合、建议相关的任何操作,还提供了请求在生成的文档上突出显示的方法。
MatchAll Query使用规则和原生API相同
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("indexname"); //搜索请求元数据构建 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定查询的类型 builder.query(QueryBuilders.matchAllQuery()); //数据放入搜索请求中 request.source(builder); //rest客户端响应请求。 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); //打印命中数. System.out.println(Arrays.toString(search.getHits().getHits())); }}
Match Query使用规则和原生API相同
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定查询的类型 后面可以指定分词器等配置。 参数1:字段名,参数2:匹配内容 builder.query(QueryBuilders.matchQuery("name","zwh1").analyzer("ik_max_word")); //数据放入搜索请求中 request.source(builder); //rest客户端响应请求。 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); //打印命中数. System.out.println(Arrays.toString(search.getHits().getHits())); }}
Term Query使用规则和原生API相同
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定查询的类型 参数1:字段名,参数2:匹配内容 builder.query(QueryBuilders.termQuery("name","zwh2")); //数据放入搜索请求中 request.source(builder); //rest客户端响应请求。 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); //打印命中数. System.out.println(Arrays.toString(search.getHits().getHits())); }}
分页查询@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定查询的类型 参数1:字段名,参数2:匹配内容 builder.query(QueryBuilders.matchQuery("name","zwh1")); //对内容进行分页,from:代表从指定页的下一页开始,比如指定0则是从1开始。 //size:每次查询展示个数 builder.from(0); builder.size(2); request.source(builder); SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); System.out.println("总命中数" + search.getHits().getTotalHits()); System.out.println(Arrays.toString(search.getHits().getHits())); }}
执行查询结果 总命中3,只显示两个。
Range Query
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定范围查询 参数1:字段名。lt:小于,gt:小于。 builder.query(QueryBuilders.rangeQuery("age").lt("30").gt("21")); //数据放入搜索请求中 request.source(builder); //rest客户端响应请求。 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); System.out.println("总命中数" + search.getHits().getTotalHits()); System.out.println(Arrays.toString(search.getHits().getHits())); }}
QueyrString Query类似于Mysql模糊查询官方文档原生APIhttps://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl-query-string-query.html#query-dsl-query-string-query
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); // //指定QueryString查询 参数:查询内容,可以使用通配符* field:字段名,可以使用fields指定多个字段 builder.query(QueryBuilders.queryStringQuery("z*").field("name").); //数据放入搜索请求中 request.source(builder); //rest客户端响应请求。 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); System.out.println("总命中数" + search.getHits().getTotalHits()); System.out.println(Arrays.toString(search.getHits().getHits())); }}
BoolQuery@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //创建BoolQueryBuilder BoolQueryBuilder queryBuilder = new BoolQueryBuilder(); //给must传值 queryBuilder.must(QueryBuilders.rangeQuery("age").gt(1)); //给filter传值 queryBuilder.filter(QueryBuilders.matchQuery("name","zwh")); //数据放入搜索请求中 SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); //rest客户端响应请求。 System.out.println("总命中数" + search.getHits().getTotalHits()); System.out.println(Arrays.toString(search.getHits().getHits())); }}
高亮查询高亮查询要配合其他查询使用。
@RunWith(SpringRunner.class)@SpringBootTestpublic class ESTest { @Autowired private RestHighLevelClient restHighLevelClient; @Test public void tes2t() throws IOException { //创建 SeachRequest。如果没有参数,这将针对所有索引运行。 参数:索引名 SearchRequest request = new SearchRequest("zwh"); // 构建搜索请求元数据 SearchSourceBuilder builder = new SearchSourceBuilder(); //指定MatchQuery查询 builder.query(QueryBuilders.matchQuery("name","zwh1")); //创建高亮查询 HighlightBuilder high = new HighlightBuilder().field("name"); //设置高亮查询 builder.highlighter(high); request.source(builder); SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT); System.out.println("总命中数" + search.getHits().getTotalHits()); System.out.println(Arrays.toString(search.getHits().getHits())); }}
查询结果