SpringBoot集成ES简单使用

SpringBoot 集成 ES 7.12.0 使用API(一)

创建Client客户端

@Configuration
public class ESConfig {

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

测试类

@SpringBootTest
class EsApiApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;
}

索引API 使用

1.创建索引

	//创建索引 client.indices().create
    @Test
    void testCreatedIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("caw_index");
        //客户端执行请求 IndicesClient,请求获得响应
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
    //输出
    //org.elasticsearch.client.indices.CreateIndexResponse@825209df

2.删除索引

	//删除索引 client.indices().delete
    @Test
    void textDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("caw_index");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged()); //true
    }

3.判断索引是否存在

	//判断索引是否存在 client.indices().exists
    @Test
    void textExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("caw_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

文档API 使用

1.创建文档

 	//创建文档 client.index
 	@Test
    void creteDocument() throws IOException {
        User user = new User("李四", 34);
        //创建请求 请求到具体的索引
        IndexRequest request = new IndexRequest("caw_index");
        //规则 put /caw_index/_doc/1 
        //设置文档id,不指定ES会随机产生
        request.id("3");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");

        //将User数据放入请求 json
        request.source(JSON.toJSONString(user), XContentType.JSON);

        //客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        System.out.println(response.toString());
        //IndexResponse[index=caw_index,type=_doc,id=id,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
        System.out.println(response.status());
        //CREATED
    }

2.查看文档

	//查看文档 client.get
    @Test
    void testGetDocument() throws IOException {
    	//查看 索引caw_index下id为1 的文档
        GetRequest request = new GetRequest("caw_index","1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //打印文档内容  {"age":34,"name":"李四"}
        System.out.println(response.getSourceAsString());
        //返回全部内容 和命令行一样
        //{"_index":"caw_index","_type":"_doc","_id":"1","_version":1,"_seq_no":6,"_primary_term":1,"found":true,"_source":{"age":22,"name":"常奥文"}}
        System.out.println(response);
    }

3.判断文档是否存在

	//判断文档是否存在 client.exists
    @Test
    void testIsExists() throws IOException {
        GetRequest request = new GetRequest("caw_index", "1");
        request.fetchSourceContext(new FetchSourceContext(false));

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

4.修改文档

	//修改文档 client.update
    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("caw_index", "1");
        User user = new User("李四学java",23);
        //将修改的内容放入请求体 也就是 doc中
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

5.删除文档

 	//删除文档 client.delete
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("caw_index", "id");
        request.timeout("1s");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

6.批量操作文档

	//批量添加   BulkRequest  client.bulk
    @Test
    void testBulkDocument() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");

        ArrayList<User> list = new ArrayList<>();
        list.add(new User("请求", 11));
        list.add(new User("亲戚", 13));
        list.add(new User("融入", 10));
        list.add(new User("一哦", 23));
        list.add(new User("一样", 45));
        list.add(new User("看看", 67));
        list.add(new User("到底", 3));

        for (int i = 0; i < list.size(); i++) {
            request.add(new IndexRequest("caw_index")
                    .id(""+i)
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        client.bulk(request, RequestOptions.DEFAULT);
    }

在这里插入图片描述
BulkRequest可执行多种操作 具体New相对应的请求

7.文档集合查询

	//集合查询 SearchRequest   client.search
    @Test
    void testSearchDocument() throws IOException {
        SearchRequest request = new SearchRequest("caw_index");
        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //查询条件 QueryBuilders
        //精准搜索  termQuery
        //所有搜索   matchAllQuery

		//精准查询  name 包含 “一”
//        TermQueryBuilder query = QueryBuilders.termQuery("name", "一");
		//查询所有
        MatchAllQueryBuilder allQuery = QueryBuilders.matchAllQuery();
        builder.query(allQuery);
        builder.from(0);		//分页 pageIndex  有默认值
        builder.size(5);		//分页 pageSize
        builder.sort("age", SortOrder.DESC);	//排序
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
	
		//将搜索条件 放入请求中
        request.source(builder);
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(search.getHits()));
        System.out.println("=========================");
        ArrayList<Object> list = new ArrayList<>();
        for (SearchHit hit: search.getHits().getHits()) {
            list.add(hit.getSourceAsString());
        }
        System.out.println(list);
    }

8. 复杂查询(条件,区间,排序,分页,字段过滤)

public List searchDocumentById(String taskId, Date startTime) {
        //构建 查询请求
        SearchRequest request = new SearchRequest(indexName);
        //创建查询对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		// taskId = 
		// 注意 如果查询字段类型为 keyword 则需在字典后添加.keyword
        TermQueryBuilder termQuery = QueryBuilders.termQuery("taskId.keyword", taskId);
        boolQuery.must(termQuery);

        if (startTime != null) {
        	//date >=  and date <
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("date");
            rangeQuery.gte(startTime).lt(new Date(startTime.getTime() + 5000));
            boolQuery.must(rangeQuery);
        }

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 分页
        sourceBuilder.from(0);
        sourceBuilder.size(3000);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 排序
        sourceBuilder.sort("date", SortOrder.ASC);
        // 字段过滤
        // 参数一: 需要的字段
        // 参数二: 不需要的字段
        sourceBuilder.fetchSource(new String[]{"msg", "date"}, null);
        sourceBuilder.query(boolQuery);

        request.source(sourceBuilder);

        ArrayList list = new ArrayList();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                list.add(hit.getSourceAsMap());
            }
        } catch (Exception e) {
            throw new ServiceException("日志查询错误");
        }
        return list;
    }

更多资料

更加详细的文档API请参考ES聚合查询

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值