当前位置: 代码迷 >> 综合 >> ElasticSearch7.6.1 实际操作
  详细解决方案

ElasticSearch7.6.1 实际操作

热度:61   发布时间:2024-01-04 02:32:08.0

目录

 

pom.xml

ElasticsearchConfig.class

User.class

DemoApplicationTests.class


  • pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.5.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.run.elasticsearch</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
  • ElasticsearchConfig.class

package com.run.elasticsearch.demo.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;@Configuration
public class ElasticsearchConfig {@Beanpublic RestHighLevelClient restHighLevelClient() {RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));return restHighLevelClient;}
}
  • User.class

package com.run.elasticsearch.demo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {private String name;private int age;}
  • DemoApplicationTests.class

package com.run.elasticsearch.demo;import com.alibaba.fastjson.JSON;
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.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;@SpringBootTest
class DemoApplicationTests {// 面向对象来操作@Autowired@Qualifier("restHighLevelClient")private RestHighLevelClient client;// 测试索引的创建 Request PUT dong_index@Testvoid testCreateIndex() throws IOException {// 1、创建索引请求CreateIndexRequest request = new CreateIndexRequest("dong_index");// 2、客户端执行请求 IndicesClient,请求后获得响应CreateIndexResponse createIndexResponse =client.indices().create(request, RequestOptions.DEFAULT);System.out.println(createIndexResponse);}// 测试获取索引,判断其是否存在@Testvoid testExistIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("dong_index2");boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);System.out.println(exists);}// 测试删除索引@Testvoid testDeleteIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest("dong_index");// 删除AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);System.out.println(delete.isAcknowledged());}// 测试添加文档@Testvoid testAddDocument() throws IOException {// 创建对象User user = new User("复东", 23);// 创建请求IndexRequest request = new IndexRequest("dong_index");// 规则 put /dong_index/_doc/1request.id("1");request.timeout(TimeValue.timeValueSeconds(1));request.timeout("1s");// 将我们的数据放入请求 jsonrequest.source(JSON.toJSONString(user), XContentType.JSON);// 客户端发送请求 , 获取响应的结果IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT);System.out.println(indexResponse.toString()); //System.out.println(indexResponse.status()); // 对应我们命令返回的状态}// 获取文档,判断是否存在 get /index/doc/1@Testvoid testIsExists() throws IOException {GetRequest getRequest = new GetRequest("dong_index", "1");
// 不获取返回的 _source 的上下文了getRequest.fetchSourceContext(new FetchSourceContext(false));getRequest.storedFields("_none_");boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);System.out.println(exists);}
//    // 获得文档的信息@Testvoid testGetDocument() throws IOException {GetRequest getRequest = new GetRequest("dong_index", "1");GetResponse getResponse = client.get(getRequest,RequestOptions.DEFAULT);System.out.println(getResponse.getSourceAsString()); // 打印文档的内容System.out.println(getResponse); // 返回的全部内容和命令式一样的}// 更新文档的信息@Testvoid testUpdateRequest() throws IOException {UpdateRequest updateRequest = new UpdateRequest("dong_index","1");updateRequest.timeout("1s");User user = new User("复东Java", 18);updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);UpdateResponse updateResponse = client.update(updateRequest,RequestOptions.DEFAULT);System.out.println(updateResponse.status());}// 删除文档记录@Testvoid testDeleteRequest() throws IOException {DeleteRequest request = new DeleteRequest("dong_index","1");request.timeout("1s");DeleteResponse deleteResponse = client.delete(request,RequestOptions.DEFAULT);System.out.println(deleteResponse.status());}// 特殊的,真的项目一般都会批量插入数据!@Testvoid testBulkRequest() throws IOException {BulkRequest bulkRequest = new BulkRequest();bulkRequest.timeout("10s");ArrayList<User> userList = new ArrayList<>();userList.add(new User("dong1",3));userList.add(new User("dong2",3));userList.add(new User("dong3",3));userList.add(new User("sina1",3));userList.add(new User("sina1",3));userList.add(new User("sina1",3));
// 批处理请求for (int i = 0; i < userList.size() ; i++) {
// 批量更新和批量删除,就在这里修改对应的请求就可以了bulkRequest.add(new IndexRequest("dong_index").id(""+(i+1)).source(JSON.toJSONString(userList.get(i)), XContentType.JSON));}BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);System.out.println(bulkResponse.hasFailures()); // 是否失败,返回 false 代表成功!}// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!@Testvoid testSearch() throws IOException {SearchRequest searchRequest = new SearchRequest("dong_index");
// 构建搜索条件SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.highlighter();
// 查询条件,我们可以使用 QueryBuilders 工具来实现
// QueryBuilders.termQuery 精确
// QueryBuilders.matchAllQuery() 匹配所有TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","sina1");
// MatchAllQueryBuilder matchAllQueryBuilder =QueryBuilders.matchAllQuery();sourceBuilder.query(termQueryBuilder);sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));searchRequest.source(sourceBuilder);SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);System.out.println(JSON.toJSONString(searchResponse.getHits()));System.out.println("=================================");for (SearchHit documentFields : searchResponse.getHits().getHits()) {System.out.println(documentFields.getSourceAsMap());}}}