0
点赞
收藏
分享

微信扫一扫

ElasticSearch 入门 (三)

阎小妍 2022-01-31 阅读 115

前言

编写配置类:

@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<User> 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();
    }

}
举报

相关推荐

0 条评论