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

    }
相关推荐
风落无尘3 小时前
《智能重生:从垃圾堆到AI工程师》——第二章 概率与生存
大数据·人工智能
档案宝档案管理3 小时前
无缝对接财务软件,实现会计档案全流程自动化流转
大数据
juniperhan3 小时前
Flink 系列第21篇:Flink SQL 函数与 UDF 全解读:类型推导、开发要点与 Module 扩展
java·大数据·数据仓库·分布式·sql·flink
科研前沿3 小时前
2026 数字孪生前沿科技:全景迭代报告 —— 镜像视界生成式孪生(Generative DT)技术白皮书
大数据·人工智能·科技·算法·音视频·空间计算
Elastic 中国社区官方博客4 小时前
Elastic-caveman : 在不损失 Elastic 最佳效果的情况下,将 AI 响应 tokens 减少64%
大数据·运维·数据库·人工智能·elasticsearch·搜索引擎·全文检索
互联网推荐官4 小时前
上海软件定制开发全流程拆解:需求分析、技术选型与交付管理的工程实践
大数据·数据库·需求分析
samFuB4 小时前
【数据集】分省农林牧渔总产值、农业总产值数据(2007-2024年)
大数据
云天AI实战派5 小时前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
m0_466525296 小时前
酷特AGI:从“自家试验田”到“全球输出”
大数据·人工智能·agi
市象6 小时前
AI带给TCL空调的头部假想
大数据·人工智能