springboot整合ES

(1)创建一个Springboot工程并加入相关的依赖

<dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


(2) 创建一个配置,获取ES工具类对象。

@Configuration
public class ESConfig {

    //该对象可以对我们的ES进行相关的操作
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
        return client;
    }
}

(3)进行相关对ES操作

3.1 操作索引---创建索引

    //PUT  /索引名称
    @Test
    void testCreateIndex() throws Exception {
        //该类把创建索引的信息都封装到该类中
        CreateIndexRequest createIndexRequest=new CreateIndexRequest("qy151-index");
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged());
    }

3.2 操作索引--删除索引

 @Test
    public void testDeleteIndex() throws Exception {
        DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest("qy151-index");
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

3.3 索引操作--判断索引是否存在

@Test
    public void testIndexExists() throws Exception{
        GetIndexRequest getIndexRequest=new GetIndexRequest("qy151-index");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

(4)操作文档---添加文档

    //添加文档--PUT /索引/1 {name:"",age:"",address:""}
    @Test
    public void testInsertDoc() throws Exception{
        IndexRequest indexRequest=new IndexRequest("qy151-index");
        indexRequest.id("1");//指定文档的id
        //指定文档的内容:String文档的json内容,XContentType xContentType:以什么格式
        indexRequest.source(JSON.toJSONString(new User("张三","北京",22)), XContentType.JSON);

        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.getResult());
    }

(5)查询文档--id

 //获取文档 GET /索引/_doc/1
    @Test
    public void testGetDoc() throws Exception{
        GetRequest indexRequest=new GetRequest("qy151-index");
        indexRequest.id("1");
        GetResponse getResponse = client.get(indexRequest, RequestOptions.DEFAULT);
        String string = getResponse.getSourceAsString();
        User user = JSON.parseObject(string, User.class);

        Map<String, Object> map = getResponse.getSourceAsMap();
        System.out.println(map.get("address"));
    }

(6)判断文档是否存在

 //判断索引文档是否存在
    @Test
    public void testDocExist() throws Exception{
        GetRequest indexRequest=new GetRequest("qy151-index");
        indexRequest.id("2");
        boolean exists = client.exists(indexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

(7)删除文档

//文档操作---删除文档
    @Test
    public void testDeleteDoc() throws Exception{
        DeleteRequest deleteRequest=new DeleteRequest("qy151-index");
        deleteRequest.id("1");
        DeleteResponse delete = client.delete(deleteRequest,RequestOptions.DEFAULT);

        System.out.println(delete.getResult());
    }

(8)修改文档

 @Test
    public void testUpdateDoc()throws  Exception{
        UpdateRequest updateRequest=new UpdateRequest("qy151-index","1");
        User user = new User();
        user.setName("柯莱");
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.getResult());
    }

(9)批量添加文档

//批量添加
    @Test
    public void testBuck() throws Exception{
        BulkRequest bulk = new BulkRequest("qy151-index");
        List<User> list = new ArrayList<>();
        list.add(new User("5","胡桃","往生堂",18));
        list.add(new User("6","甘雨","月海亭",1800));
        list.add(new User("7","甘雨02","月海亭02",1802));
        list.add(new User("8","甘雨03","月海亭03",1803));

        list.stream().forEach(item->bulk.add(new IndexRequest().id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
//        for (User user:list){
//            IndexRequest indexRequest = new IndexRequest();
//            indexRequest.id(user.getId());
//            indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
//            bulk.add(indexRequest);
//        }


        BulkResponse bulkResponse = client.bulk(bulk,RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());
    }

(10)复杂查询

@Test
    public void testSearch() throws Exception{
        //
        SearchRequest searchResult = new SearchRequest("qy151-index");
        //创建一个条件对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name","甘");
        sourceBuilder.query(matchQuery);
        
        //分页
        sourceBuilder.from(0);
        sourceBuilder.size(10);

        //排序
       // sourceBuilder.sort("age");

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);

        searchResult.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchResult,RequestOptions.DEFAULT);
        System.out.println("总条数"+searchResponse.getHits().getTotalHits().value);
        SearchHit[] hits = searchResponse.getHits().getHits();
        Arrays.stream(hits).forEach(item-> System.out.println(item.getSourceAsString()));
        Arrays.stream(hits).forEach(item-> System.out.println(item.getHighlightFields()));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值