ElasticSearch 入门 (三)

ElasticSearch 入门 (三),第1张

ElasticSearch 入门 (三) 前言

SpringBoot 整合 ElasticSearch 。

依赖如下:


    org.elasticsearch.client
    elasticsearch-rest-high-level-client
    7.16.3


    org.elasticsearch.client
    elasticsearch-rest-client
    7.16.3


    org.elasticsearch
    elasticsearch
    7.16.3

SpringBoot 整合 ElasticSearch

编写配置类:

@Configuration
public class ElasticsearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}
增删改查以及批量 *** 作
@RestController
public class TestElasticsearchController {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("/testCreateIndex")
    public String testCreateIndex() throws IOException {
        // 1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("student");
        // 2.客户端执行请求,请求后获的响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return createIndexResponse.toString();
    }

    @RequestMapping("/testExistIndex")
    public String testExistIndex() throws IOException {
        // 1.获取索引请求
        GetIndexRequest request = new GetIndexRequest("student");
        // 2.客户端执行请求,请求后获的响应
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        return exists + "";
    }

    @RequestMapping("/testDeleteIndex")
    public String testDeleteIndex() throws IOException {
        // 1.删除索引请求
        DeleteIndexRequest request = new DeleteIndexRequest("student");
        // 2.客户端执行请求,请求后获的响应
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return delete.isAcknowledged() + "";
    }

    //  文档 *** 作
    // 创建文档
    @RequestMapping("/testAdddocument")
    public String testAdddocument() throws IOException {
        // 1.创建对象
        User user = new User("张三", 3);
        // 2.创建请求
        IndexRequest request = new IndexRequest("student");
        // 3.设置规则 put/kuang_index/_doc/1
        request.id("1");
        request.timeout(Timevalue.timevalueSeconds(1));
        // 4.数据放入请求 json
        request.source(JSON.toJSonString(user), XContentType.JSON);
        // 5.客户端发送请求,获取响应结果
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        return indexResponse.toString();
    }

    // 获取文档 ,判断是否存在 GET /index/_doc/1
    @RequestMapping("/testIsExistsdocument")
    public String testIsExistsdocument() throws IOException {

        GetRequest getRequest = new GetRequest("student", "1");
        // 过滤 _source
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");

        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        return exists + "";
    }

    // 获取文档信息
    @RequestMapping("/testGetdocument")
    public String testGetdocument() throws IOException {

        GetRequest getRequest = new GetRequest("student", "1");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);

        return documentFields.getSourceAsString() + "";
    }

    // 更新文档信息
    @RequestMapping("/testUpdatedocument")
    public String testUpdatedocument() throws IOException {

        UpdateRequest updateRequest = new UpdateRequest("student", "1");
        updateRequest.timeout("1s");
        User user = new User("张三", 3);
        updateRequest.doc(JSON.toJSonString(user), XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return update.status() + "";
    }

    // 删除文档信息
    @RequestMapping("/testDeletedocument")
    public String testDeletedocument() throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("student", "1");
        deleteRequest.timeout("1s");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return delete.status() + "";
    }

    // 批量插入
    @RequestMapping("/testBatchInsertdocument")
    public String testBatchInsertdocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList list = new ArrayList<>();
        list.add(new User("迪迦1", 24));
        list.add(new User("迪迦2", 24));
        list.add(new User("迪迦3", 24));
        list.add(new User("迪迦4", 24));
        list.add(new User("奥特曼1", 24));
        list.add(new User("猪亮宇", 20));
        list.add(new User("猪亮宇1", 20));
        list.add(new User("猪亮宇2", 24));
        list.add(new User("猪亮宇3", 24));
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("student")
                    .id("" + (i + 1))
                    .source(JSON.toJSonString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return responses.hasFailures() + "";
    }
    // 查询
    @RequestMapping("/testSearch")
    public String testSearch() throws IOException {

        SearchRequest searchRequest = new SearchRequest("student");
        // 构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询条件,我们可以使用QueryBuilders 工具来实现
        // QueryBuilders.matchAllQuery() 匹配所有
        // QueryBuilders.termQuery 精确匹配
        // 中文被标准分词器分词了, 所以这里查询的时候要用 keyword
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", "迪迦1");

        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS));
        sourceBuilder.from();
        sourceBuilder.size();
        searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSonString(search.getHits()));
        System.out.println("==========================");
        for (SearchHit documentFields : search.getHits().getHits()){
            System.out.println(documentFields.getSourceAsMap().toString());
        }

        return search.getHits().getHits().toString();
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5716219.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存