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

    }
相关推荐
linmoo19861 小时前
Flink 系列之二十二 - 高级概念 - 保存点
大数据·flink·savepoint·保存点
试剂界的爱马仕3 小时前
TCA 循环中间体如何改写肝损伤命运【AbMole】
大数据·人工智能·科技·机器学习·ai写作
Leo.yuan3 小时前
数据湖是什么?数据湖和数据仓库的区别是什么?
大数据·运维·数据仓库·人工智能·信息可视化
hao_wujing4 小时前
基于梯度的中毒攻击
大数据·人工智能
qq_4639448616 小时前
【Spark征服之路-2.2-安装部署Spark(二)】
大数据·分布式·spark
三劫散仙16 小时前
kubernetes jenkins pipeline优化拉取大仓库性能指定分支+深度
容器·kubernetes·jenkins
weixin_5051544616 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
打码人的日常分享17 小时前
智慧城市建设方案
大数据·架构·智慧城市·制造
阿里云大数据AI技术19 小时前
ES Serverless 8.17王牌发布:向量检索「火力全开」,智能扩缩「秒级响应」!
大数据·运维·serverless
Mikhail_G19 小时前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析