ES(elasticsearch)

文章目录

介绍

Elasticsearch 是一个分布式、RESTful 风格的搜索和数据分析引擎,它能够快速地存储、搜索和分析大量的数据。Elasticsearch 常用于全文搜索、结构化搜索、日志分析、实时应用监控等场景。

在springboot项目集成ES

操作步骤

1.创建boot项目

引入入Web(Spring Web)NoSQl(Spring Data Elasticsearch(Access+Driver))
2.引入依赖

复制代码
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version> <!-- 确认版本 -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.编写配置类

复制代码
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 {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}

4.启动ES,编写测试类
创建索引

复制代码
 @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 创建索引
     */
    @Test
    void testCreateIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("zyy_index");
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        // 查看是否创建成功
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println(acknowledged);
        client.close();
    }

查询索引

复制代码
@Test
    void testGetIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("zyy_index");
        // 索引是否存在
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
        client.close();
    }

删除索引

复制代码
@Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("zyy_index");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        // 是否删除成功
        boolean acknowledged = delete.isAcknowledged();
        System.out.println(acknowledged);
        client.close();
    }

文档的添加

复制代码
@Test
    void testAddDoc() throws IOException {
        User user = new User("zyy", 18);

        IndexRequest indexRequest = new IndexRequest("zyy_index");
        //类似PUT /zyy_index/_doc/1
        indexRequest.id("1");
        indexRequest.timeout(TimeValue.timeValueMillis(1000));
        indexRequest.source(JSON.toJSONString(user), XContentType.JSON);

        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        // 返回状态CREATED
        System.out.println(indexResponse.status());
        //IndexResponse[index=zyy_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
        System.out.println(indexResponse);

    }

文档信息的获取

复制代码
@Test
    void testGetDoc() throws IOException {
        // 类似GET /zyy_index/_doc/1
        GetRequest request = new GetRequest("zyy_index", "1");

        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());
    }

文档的获取,并判断其是否存在

复制代码
@Test
    void testDocIsExits() throws IOException {
        // 类似GET /zyy_index/_doc/1
        GetRequest request = new GetRequest("zyy_index", "1");
        // 不获取返回的 _source的上下文了
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");

        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

文档的更新

复制代码
@Test
    void testUpdateDoc() throws IOException {
        User user = new User("zyy", 19);

        UpdateRequest request = new UpdateRequest("zyy_index", "1");
        request.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response);
    }

文档的删除

复制代码
 @Test
    void testDeleteDoc() throws IOException {
        DeleteRequest request = new DeleteRequest("zyy_index", "1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
        System.out.println(response);
    }

文档的查询

复制代码
@Test
    void testSearch() throws IOException {
        //精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zyy");
        TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery("_index", "zyy_index");
        //匹配查询
//		MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "zyy");
        //构建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.query(termQueryBuilder1);
        //设置高亮
		sourceBuilder.highlighter(new HighlightBuilder());
        //设置分页
//		sourceBuilder.from(0);
//		sourceBuilder.size(10);
        //请求对象
        SearchRequest request = new SearchRequest();
        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //查看返回
        SearchHits hits = response.getHits();
        System.out.println(JSON.toJSONString(hits));
        System.out.println("========================");
        for (SearchHit hit : hits.getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
        System.out.println("========================");
    }

批量添加数据

复制代码
@Test
    void testBulk() throws IOException {
        List<User> userList = new ArrayList<>();
        userList.add(new User("zyy1", 1));
        userList.add(new User("zyy2", 2));
        userList.add(new User("zyy3", 3));
        userList.add(new User("zyy4", 4));
        userList.add(new User("zyy5", 5));
        userList.add(new User("zyy6", 6));

        BulkRequest request = new BulkRequest();
        request.timeout("10s");
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);

            IndexRequest indexRequest = new IndexRequest("zyy_index");
            indexRequest.id("" + i);
            indexRequest.source(JSON.toJSONString(user), XContentType.JSON);

            request.add(indexRequest);
        }

        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(responses.status());

    }
相关推荐
大大大大晴天14 小时前
浅聊维度建模中的星型模型与雪花模型
大数据
数字新视界18 小时前
能耗管理系统提升企业能源效率的实践与展望
大数据·人工智能·数据中心·机房管理·模块化机房
大大大大晴天19 小时前
别让金额越算越多:事实表与维度表设计避坑指南
大数据
如夏倾城20 小时前
入侵检测系统(IDS)原理、部署模式与 IPS/防火墙对比
大数据·网络·人工智能·网络安全·云原生·架构·kubernetes
wuyk55520 小时前
Spider-第20讲-综合实战可上线爬虫
大数据·爬虫·python·elasticsearch
培培说证21 小时前
大数据与会计专业性价比高的证书有哪些?
大数据
伞伞悦读1 天前
【第90期】KNN分类回归流水线与K值对照的实验与排查
大数据·人工智能·python·深度学习·机器学习
老余说AI1 天前
跨境电商、课程出海:六款多语言视频翻译工具选型指南
大数据·运维·人工智能
starzy19901 天前
Structured Streaming 模块与编程模型:引擎内部到底由什么组成
大数据·hadoop·hdfs
Lansonli1 天前
大数据Spark(九十二):Spark WebUI介绍
大数据·分布式·spark