> 文档中心 > Springboot快速上手ElasticSearch操作

Springboot快速上手ElasticSearch操作


Springboot操作ElasticSearch

通过前面我们安装和简单使用了下ElasticSearch,今天我们试试ElasticSearch的一些基础操作,同时也是常用操作
如果你还没有安装ElasticSearch:https://blog.csdn.net/hello_list/article/details/124594867

创建一个spring boot快速项目,选上这几个:

在这里插入图片描述

具体依赖

<dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.80</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-thymeleaf</artifactId></dependency><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-test</artifactId>    <scope>test</scope></dependency></dependencies>

新建一个config配置下,类ElasticSearchClientConfig

package com.xuexiruji.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;@Configurationpublic class ElasticSearchClientConfig {    //客户端操作对象注入进来    @Bean    public RestHighLevelClient restHighLevelClient() { RestHighLevelClient client = new RestHighLevelClient(  RestClient.builder(   new HttpHost("localhost", 9200, "http"))); return client;    }}

User类

public class User {    private String name;    private int age;    @Override    public String toString() { return "User{" +  "name='" + name + '\'' +  ", age=" + age +  '}';    }    public User() {    }    public User(String name, int age) { this.name = name; this.age = age;    }    public String getName() { return name;    }    public void setName(String name) { this.name = name;    }    public int getAge() { return age;    }    public void setAge(int age) { this.age = age;    }}

注释很详细,拿去即可测试,直接上全部代码

package com.xuexiruji;import com.alibaba.fastjson.JSON;import com.sun.org.apache.regexp.internal.RE;import com.xuexiruji.pojo.User;import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;import org.elasticsearch.action.bulk.BulkRequest;import org.elasticsearch.action.bulk.BulkResponse;import org.elasticsearch.action.delete.DeleteRequest;import org.elasticsearch.action.delete.DeleteResponse;import org.elasticsearch.action.get.GetRequest;import org.elasticsearch.action.get.GetResponse;import org.elasticsearch.action.index.IndexRequest;import org.elasticsearch.action.index.IndexResponse;import org.elasticsearch.action.search.SearchRequest;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.action.support.master.AcknowledgedResponse;import org.elasticsearch.action.update.UpdateRequest;import org.elasticsearch.action.update.UpdateResponse;import org.elasticsearch.client.RequestOptions;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.common.xcontent.XContentType;import org.elasticsearch.core.TimeValue;import org.elasticsearch.index.query.QueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.index.query.TermQueryBuilder;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.builder.SearchSourceBuilder;import org.elasticsearch.search.fetch.subphase.FetchSourceContext;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.test.context.SpringBootTest;import javax.lang.model.element.VariableElement;import javax.sound.midi.Soundbank;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;@SpringBootTestclass EsTestApplicationTests {    @Autowired    @Qualifier("restHighLevelClient")    private RestHighLevelClient client;    @Test    void contextLoads() {    }    /* 创建索引   put     */    @Test    void testInsert() throws Exception { //1、创建索引 CreateIndexRequest request = new CreateIndexRequest("index_test01"); //2、执行请求 CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(createIndexResponse);    }    //获取索引    @Test    void testGetIndex() throws Exception { //1、创建requset GetIndexRequest request = new GetIndexRequest("index_test01"); //2、执行请求,判断存不存在 boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists);    }    //删除索引    @Test    void testDeleteIndex() throws Exception { //1、创建request DeleteIndexRequest request = new DeleteIndexRequest("index_test01"); //2、执行请求,返回删除结果 AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT); System.out.println(delete.toString());    }    //CRUD    //添加文档    @Test    void testInsertDocument() throws Exception {// 创建一个索引库,执行下 testInsert()方法 //1、创建对象 User user = new User("xuexiriji", 22); //2、创建请求 IndexRequest request = new IndexRequest("index_test01"); //构建请求体 put request.id("1"); request.timeout("1s");   //设置超时时间 request.source(JSON.toJSONString(user), XContentType.JSON); //发送请求,获取响应结果 IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); //查看响应结果 System.out.println(indexResponse.toString()); System.out.println(indexResponse.status());    }    //获取文档,先判断文档是否存在    @Test    void testIsExistsDocument() throws IOException { //创建请求体 GetRequest getRequest = new GetRequest("index_test01", "1"); //构建请求体,不获取返回的_source的上下文 getRequest.fetchSourceContext(new FetchSourceContext(false)); getRequest.storedFields("_none_"); //发送请求 boolean exists = client.exists(getRequest, RequestOptions.DEFAULT); System.out.println(exists);    }    //获取文档信息    @Test    void testGetDocument() throws IOException { //创建请求体 GetRequest getRequest = new GetRequest("index_test01", "1"); //发送请求,获取响应 GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT); //拿到响应,我们可以点get到的字段,都可以尝试下 System.out.println(documentFields.getSourceAsString());  //打印文档内容 System.out.println(documentFields);    //返回整个文档信息    }    //更新文档信息    @Test    //post/id/_doc    void testUpdateDocument() throws IOException { //创建请求体 UpdateRequest updateRequest = new UpdateRequest("index_test01", "6"); //构建请求体 updateRequest.timeout("1s"); //覆盖更新 User user = new User("xuexiriji", 20); //更新某字段 Map<String,Object> map = new HashMap<>(); map.put("name","xuexiriji6"); updateRequest.doc(JSON.toJSONString(map), XContentType.JSON); //发送请求,获取响应 UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT); System.out.println("============================"+updateRequest);    }    //更新文档信息    @Test    void testDeleteDocument() throws IOException { //创建请求体 DeleteRequest deleteRequest = new DeleteRequest("index_test01", "1"); //构建请求体 deleteRequest.timeout("1s"); //发送请求,获取响应 DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT); //打印响应结果 System.out.println(deleteResponse.status()); System.out.println(deleteResponse);    }    //实用    //批量插入数据    @Test    void testBulkDocument() throws IOException { //创建请求体 BulkRequest bulkRequest = new BulkRequest(); //构建请求体 bulkRequest.timeout("1s"); ArrayList<User> userArrayList = new ArrayList<>(); userArrayList.add(new User("xuexiriji1",21)); userArrayList.add(new User("xuexiriji2",21)); userArrayList.add(new User("xuexiriji3",21)); userArrayList.add(new User("xuexiriji4",21)); userArrayList.add(new User("xuexiriji5",21)); //批处理请求 for (int i=0;i<userArrayList.size();i++){     bulkRequest.add(      new IndexRequest("index_test01")      .id(""+(i+1))      .source(JSON.toJSONString(userArrayList.get(i)),XContentType.JSON)     ); } //发送请求,获取响应 BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT); //打印响应结果 System.out.println(bulkResponse.status()); System.out.println(bulkResponse);    }    //查询    @Test    void testSearch() throws IOException { //1、创建搜索请求 SearchRequest searchRequest = new SearchRequest("index_test01"); //2、构建搜索体,搜索条件 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //我们可以点searchSourceBuilder里面的所有条件,比如查询需要构造一个条件构造器 //QueryBuilders.termQuery()精确查询 //QueryBuilders.matchAllQuery() 匹配所有 TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "xuexiriji3"); //将条件放入 searchSourceBuilder.query(termQuery); searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //超时60s,高并发下使用高并发响应 //将请求体放入 searchRequest.source(searchSourceBuilder); //3、发送请求,并获取响应 SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); //4、打印结果 System.out.println(JSON.toJSONString(searchResponse.getHits())); System.out.println("========================================="); //打印下hit中数据 for (SearchHit hit : searchResponse.getHits()) {     System.out.println(hit.getSourceAsMap()); }    }}

书法艺术字体