elastic search

Elasticsearch

基本操作

依赖

 		<dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.2.3</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.json</artifactId>
            <version>2.0.1</version>
        </dependency>

存记录用

package com.hhm;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.hhm.pojo.Deep;
import com.hhm.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class ESApplicationTest {


    /*
     *  跟postman写法基本很像
     */

    @Autowired
    ElasticsearchClient client;


    //创建索引   indices意思是:指标
    @Test
    public void addIndex() throws IOException {
        //写法1、
        CreateIndexResponse indexResponse = client.indices().create(c -> c.index("user"));
        System.out.println(indexResponse.acknowledged());


        //这种叫做构建器方式来构建对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index("test5").build();

        //写法2、 获取索引客户端
        ElasticsearchIndicesClient indices = client.indices();
        indices.create(createIndexRequest);


    }


    //查询索引
    @Test
    public void getIndex() throws IOException {
        GetIndexResponse getIndexResponse = client.indices().get(c -> c.index("user"));
        System.out.println(getIndexResponse);
    }


    //判断索引是否存在
    @Test
    public void exists() throws IOException {
        BooleanResponse booleanResponse = client.indices().exists(c -> c.index("user"));
        System.out.println(booleanResponse.value());
    }

    //删除索引
    @Test
    public void delete() throws IOException {
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(c -> c.index("user"));
        //返回为true
        System.out.println(deleteIndexResponse.acknowledged());
    }


    //文档操作
    @Test//新增
    public void addDocumentTest() throws IOException {
        User user = new User("zs", 16, "北京市朝阳区");
        IndexResponse addDoc = client.index(i -> i.index("user")
                .id("2")
                .document(user));
    }

    @Test//文档更新
    public void updateDocumentTest() throws IOException {
        User user = new User("xb", 222, "北京市昌平区");
        //索引为 user 文档id为 需要更改的文档内容 , 返回的类型
        UpdateResponse<User> update = client.update(u -> u.index("user").id("2").doc(user), User.class);
        System.out.println(update);
    }


    @Test//文档是否存在
    public void existsDocumentTest() throws IOException {
        BooleanResponse booleanResponse = client.exists(e -> e.index("user").id("1"));
        System.out.println(booleanResponse.value());

    }

    @Test//文档是否存在
    public void queryDocumentTest() throws IOException {
        //简便写法 Function接口
        GetResponse<User> getResponse = client.get(g -> g.index("user").id("2"), User.class);
        System.out.println(getResponse.source());

        //麻烦写法 Request类
        GetRequest user = new GetRequest.Builder().index("user").id("1").build();
        System.out.println(client.get(user, User.class).source());


    }


    //文档批量插入
    @Test//批量插入
    public void bulkDocumentTest() throws IOException {

        //无id插入
        List<User> users = new ArrayList<>();
        users.add(new User("hello spring", 11, "四川省"));
        users.add(new User("hello boot", 12, "山东省"));
        users.add(new User("hello c++", 13, "广东省"));
        users.add(new User("broth hello", 14, "广西省"));
        users.add(new User("helloWorld", 15, "湖北省"));
        List<BulkOperation> bulkOperations = new ArrayList<>();
        //将创建的文档放入 bulk中
        for (User user : users) {
            //索引指定文档
            bulkOperations.add(BulkOperation.of(b -> b.index(i -> i.document(user))));
        }
        //将集合的文档全部添加到user索引里面
        BulkResponse bulkResponse = client.bulk(b -> b.index("user").operations(bulkOperations));
        System.out.println(bulkResponse.took());

        //有id插入 向集合添加数据
//        bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(new User("user6",16,"中国")).id("1").index("user")).build());
//        bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(new User("user6",16,"中国")).id("2").index("user")).build());
//        bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(new User("user6",16,"中国")).id("3").index("user")).build());
//        client.bulk(b -> b.index("user").operations(bulk(users,bulkOperations,"2")));


    }

    //批量操作带id简化写
    public List<BulkOperation> bulk(List<User> users, List<BulkOperation> bulkOperations, String id) {
        //这里id设计死掉如果开发中就不需要指定id 由系统自己生成
        users.forEach(u -> bulkOperations.add(new BulkOperation.Builder().create(d -> d.document(new User(u.getName(), u.getAge(), u.getAddress())).id(id).index("user")).build()));

        return bulkOperations;
    }


    //查询
    @Test
    public void SearchTest() throws IOException {
        SearchResponse<User> search = client.search(s -> s
                        .index("user")
                        //查询name 字段包含 hello 的document(不使用分词器精确查找)
                        .query(q -> q
                                .term(t -> t
                                        .field("name")
                                        .value(v -> v.stringValue("hello"))
                                ))
                        //分页查询 从第0页开始到第三页
                        .from(0)
                        .size(20)
                        //按age 降序排序
                        .sort(f -> f.field(o -> o.field("age").order(SortOrder.Desc)))
                , User.class);

        //打印输出查到的内容
        for (Hit<User> hit : search.hits().hits()) {
            System.out.println(hit.source());
        }
    }


    //查询
    @Test
    public void matchQuery() throws IOException {
        SearchResponse<Deep> deep = client.search(s -> s
                        .index("deep")
                        .query(q -> q
                                .match(m -> m
                                        .field("name")
                                        .query("zhang")
                                )
                        )
                , Deep.class);

        deep.hits().hits().forEach(System.out::println);

    }


    //复合查询
    @Test // (li && 18) || zhang
    public void boolQuery() throws IOException {
        SearchResponse<Deep> search = client.search(s -> s
                        .index("deep")
                        .query(q -> q
                                .bool(b -> b
                                        //或
                                        .should(sl -> sl
                                                .bool(bl -> bl
                                                        //并
                                                        .must(m -> m
                                                                .match(ma -> ma
                                                                        .field("name")
                                                                        .query("li")
                                                                        .field("age")
                                                                        .query(18)
                                                                )
                                                        )

                                                )
                                        )
                                        //或
                                        .should(sl -> sl
                                                .match(ma -> ma
                                                        .field("name")
                                                        .query("zhang")
                                                )
                                        )

                                )
                        )
                , Deep.class);

        search.hits().hits().forEach(System.out::println);
    }


    //分页查询无条件  跟postman写法基本很想
    @Test
    public void SearchTestAllNoWhere() throws IOException {
        SearchResponse<User> user = client.search(s -> s.index("user").query(q -> q.matchAll(m -> m)).from(0).size(4), User.class);
        System.out.println(user.took());
        System.out.println(user.hits().total().value());
        user.hits().hits().forEach(e -> System.out.println(e.source().toString()));
    }


    @Test//范围查询
    public void SearchFromTo() throws IOException {
        SearchResponse<Deep> search = client.search(s -> s
                        //索引
                        .index("deep")
                        //查询
                        .query(q -> q
                                //范围
                                .range(r -> r
                                        //字段
                                        .field("age")
                                        //从开始           到那
                                        .from("10").to("30")
                                )
                        )
                , Deep.class);
        search.hits().hits().forEach(System.out::println);
    }

    //聚合操作
    @Test
    public void aggsTest() throws IOException {
        SearchResponse<Map> search = client.search(s -> s
                        .index("deep")
                        //分组  组取名字
                        .aggregations("ageGroup", a -> a
                                .terms(t -> t
                                        .field("age")
                                )
                        )
                        .aggregations("sum", ag -> ag
                                .sum(_s -> _s
                                        .field("age")
                                )
                        )
                        .size(0)
                , Map.class);
        System.out.println(search);
    }

    @Test
    public void xian() {
        new Thread(() -> System.out.println("高科技国际化疯狂的")).start();
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值