spring boot 项目中搭建 ElasticSearch 中间件 二 Java api 操作 es

Java api 操作 es

      • 1. 准备
      • 2. 环境
      • 3. Java操作索引
        • 3.1 创建索引
        • 3.2 查看索引
        • 3.3 删除索引
      • 4. java操作文档
        • 4.1 添加文档
        • 4.2 查询文档
        • 4.3 查询全部文档
        • 4.4 更新文档
        • 4.5 删除文档
        • 4.6 批量插入文档
        • 4.7 批量删除文档
        • 4.8 条件查询文档
        • 4.9 组合查询文档
        • 4.10 模糊查询文档

本文是进行ElasticSearch 的环境准备和基础操作(使用postman)之后,使用Java进行ElasticSearch 操作的文章。
ElasticSearch 系列文章目的是使用ElasticSearch结合spring boot项目实现项目的搜索功能。
系列文章 :

spring boot 项目中搭建 ElasticSearch 中间件 一 postman 操作 es
spring boot 项目中搭建 ElasticSearch 中间件 三 spring data 操作 es

1. 准备

首先要创建一个Java maven工程

导入以下依赖:

 
 <dependency>
     <groupId>org.elasticsearchgroupId>
     <artifactId>elasticsearchartifactId>
     <version>7.10.0version>
 dependency>
 <dependency>
     <groupId>org.elasticsearch.clientgroupId>
     <artifactId>elasticsearch-rest-high-level-clientartifactId>
     <version>7.10.0version>
 dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.9version>
dependency>

创建一个es client 后面的操作都是使用这个RestHighLevelClient

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

写一个简单的实体类,用于与es结构对应

public class Event {
    private Long id;
    private String name;
    private String type;
    private String place;
    private String phone;
    private String mail;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getPlace() {
        return place;
    }
    public void setPlace(String place) {
        this.place = place;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    @Override
    public String toString() {
        return "Event{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", place='" + place + '\'' +
                ", phone='" + phone + '\'' +
                ", mail='" + mail + '\'' +
                '}';
    }
}

2. 环境

本文使用 elasticsearch-7.10.0
不同的jdk版本要使用适配的es版本
最新es与jdk适配图

elasticsearch-7.10.0-windows-x86_64\elasticsearch-7.10.0\bin

下载后在bin中点击 elasticsearch.bat 启动es
默认端口是9200

3. Java操作索引

3.1 创建索引

注:以下操作 以索引名为event为例
注:入参client为前面创建的RestHighLevelClient
注:MyLog.logger是我自己的log插件,可以替换使用普通sout输出

private void insertDoc(RestHighLevelClient client) throws IOException {
        //插入文档
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("event").id("1001");

        Event event = new Event();
        event.setName("赛事");
        event.setType("攻击");
        ObjectMapper mapper = new ObjectMapper();
        String jsonArr = mapper.writeValueAsString(event);
        indexRequest.source(jsonArr, XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("插入文档 状态 :" + indexResponse.getResult() + " 响应 :" + jsonArr);
    }

3.2 查看索引

private void searchIndex(RestHighLevelClient client) throws IOException {
        //查询索引
        GetIndexRequest userRequest = new GetIndexRequest("event");
        GetIndexResponse getIndexResponse = client.indices().get(userRequest, RequestOptions.DEFAULT);
        //响应状态
        Map<String, List<AliasMetadata>> aliases = getIndexResponse.getAliases();
        Map<String, MappingMetadata> mappings = getIndexResponse.getMappings();
        Map<String, Settings> settings = getIndexResponse.getSettings();
        MyLog.logger.info("查询索引 响应 :" + aliases + mappings + settings);
    }

3.3 删除索引

  private void deleteIndex(RestHighLevelClient client) throws IOException {
        //删除索引
        DeleteIndexRequest userRequest = new DeleteIndexRequest("event");
        AcknowledgedResponse response = client.indices().delete(userRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("删除索引 状态 :" + response.isAcknowledged());
    }

4. java操作文档

4.1 添加文档

注:以下操作 以索引名为event为例

private void insertDoc(RestHighLevelClient client) throws IOException {
        //插入文档
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("event").id("1001");

        Event event = new Event();
        event.setName("赛事");
        event.setType("攻击");

        ObjectMapper mapper = new ObjectMapper();
        String jsonArr = mapper.writeValueAsString(event);
        indexRequest.source(jsonArr, XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("插入文档 状态 :" + indexResponse.getResult() + " 响应 :" + jsonArr);
    }

4.2 查询文档

 private void getDoc(RestHighLevelClient client, String id) throws IOException {
        //查询文档
        GetRequest getRequest = new GetRequest();
        getRequest.index("event").id(id);
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("查询文档 响应 :" + getResponse.getSourceAsString());
    }

4.3 查询全部文档

private void searchDoc(RestHighLevelClient client) throws IOException {
        //查询全部文档
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("event");
        searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //响应状态
        SearchHits hits = searchResponse.getHits();
        MyLog.logger.info("查询全部文档 响应 :" + hits.getTotalHits());
        for (SearchHit hit : hits) {
            MyLog.logger.info("查询全部文档 数据 :" + hit.getSourceAsString());
        }

    }

4.4 更新文档

 private void updateDoc(RestHighLevelClient client) throws IOException {
        //更新文档
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("event").id("1001");

        Event event = new Event();
        event.setType("防御");

        ObjectMapper mapper = new ObjectMapper();
        String jsonArr = mapper.writeValueAsString(event);
        updateRequest.doc(XContentType.JSON, "type", "防御");

        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("更新文档 状态 :" + updateResponse.getResult() + " 响应 :" + jsonArr);
    }

4.5 删除文档

 private void deleteDoc(RestHighLevelClient client) throws IOException {
        //删除文档
        DeleteRequest deleteRequest = new DeleteRequest();
        deleteRequest.index("event").id("1001");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("删除文档 响应 :" + deleteResponse.toString());
    }

4.6 批量插入文档

private void insertBatchDoc(RestHighLevelClient client, List<Event> events) throws IOException {
        //批量插入文档
        BulkRequest bulkRequest = new BulkRequest();
        for (Event event : events) {
            IndexRequest indexRequest = new IndexRequest()
                    .index("event").id(event.getId().toString())
                    .source(new ObjectMapper().writeValueAsString(event), XContentType.JSON);
            bulkRequest.add(indexRequest);
            //插入完成后立即强制刷新索引
            bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("批量插入文档 响应 :" + Arrays.toString(bulkResponse.getItems()));
    }

4.7 批量删除文档

  private void deleteBatchDoc(RestHighLevelClient client) throws IOException {
        //批量删除文档
        BulkRequest bulkRequest = new BulkRequest();
        DeleteRequest request1 = new DeleteRequest()
                .index("event").id("1002");
        DeleteRequest request2 = new DeleteRequest()
                .index("event").id("1003");
        bulkRequest.add(request1).add(request2);
        //删除完成后立即强制刷新索引
        bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        //响应状态
        MyLog.logger.info("批量删除文档 响应 :" + Arrays.toString(bulkResponse.getItems()));
    }

4.8 条件查询文档

private void searchTermDoc(RestHighLevelClient client) throws IOException {
        //查询条件文档
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("event");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //条件
        searchSourceBuilder.query(QueryBuilders.termQuery("type", "128"));
        //分页
        searchSourceBuilder.size(5);
        searchSourceBuilder.from(0);
        //排序
        searchSourceBuilder.sort("id", SortOrder.DESC);
        //管理字段
        String[] excludes = {};
        String[] includes = {"name"};
        searchSourceBuilder.fetchSource(includes, excludes);

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //响应状态
        SearchHits hits = searchResponse.getHits();
        MyLog.logger.info("查询条件文档 响应 :" + hits.getTotalHits());
        for (SearchHit hit : hits) {
            MyLog.logger.info("查询条件文档 数据 :" + hit.getSourceAsString());
        }

    }

4.9 组合查询文档

private void searchGroupDoc(RestHighLevelClient client) throws IOException {
        //组合查询文档
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("event");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("type", 13.6));
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", "北京"));
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //响应状态
        SearchHits hits = searchResponse.getHits();
        MyLog.logger.info("查询组合条件文档 响应 :" + hits.getTotalHits());
        for (SearchHit hit : hits) {
            MyLog.logger.info("查询组合条件文档 数据 :" + hit.getSourceAsString());
        }
    }

4.10 模糊查询文档

 private void searchFuzzyDoc(RestHighLevelClient client) throws IOException {
        //模糊查询文档
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("event");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "上海").fuzziness(Fuzziness.ONE);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        highlightBuilder.field("name");
        searchSourceBuilder.highlighter(highlightBuilder);

        searchSourceBuilder.query(fuzzyQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //响应状态
        SearchHits hits = searchResponse.getHits();
        MyLog.logger.info("模糊查询文档 响应 :" + hits.getTotalHits());
        for (SearchHit hit : hits) {
            MyLog.logger.info("模糊查询文档 数据 :" + hit.getSourceAsString());
        }
    }

你可能感兴趣的:(中间件,java,spring,boot,elasticsearch)