Java操作elasticsearch(3)

x33g5p2x  于2021-08-23 转载在 Java  
字(14.3k)|赞(0)|评价(0)|浏览(200)

七 Java操作ES

7.1 springboot集成ES

引入elasticsearch 依赖

	 <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!-- elasticsearch的客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>

这边没有采用 spring整合包,原因是版本控制问题, 如果项目需要按如下方式引入

 	<!--spring整合elasticsearch包-->
        <dependency>  
           <groupId>org.springframework.boot</groupId>  
           <artifactId>spring-boot-starter-data-elasticsearch</artifactId>  
       </dependency>

然后进行配置文件配置即可

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.repositories.enabled=true

配置类,写好端口,协议

/**
 * @author lsc
 * <p> </p>
 */
@Configuration
public class ElasticSearchConfig {


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

实体类

/**
 * @author lsc
 * <p> </p>
 */
public class Course {
    
    private Long id;
    
    private String name;
    
    private BigDecimal price;
    
    private String description;
    // 省略set / get
}    

7.2 索引操作

在 索引操作中只是 请求不同,其它代码均类似;

创建索引

  @Autowired
    RestHighLevelClient restHighLevelClient;

    @Test
    public void createIndex() throws IOException {
        // 创建索引 ,请求对象
        CreateIndexRequest request = new CreateIndexRequest("course");
        // 发送请求,获取响应
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        // 响应状态
        System.out.println("是否创建成功: " + acknowledged);

        // 关闭客户端连接
        restHighLevelClient.close();

    }

输出

是否创建成功: true

查看索引

    @Test
    public void viewIndex() throws IOException {
        // 查看索引请求对象
        GetIndexRequest request = new GetIndexRequest("course");
        // 发送请求取响应
        GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        Map<String, MappingMetadata> mappings = response.getMappings();
        // 响应状态
        System.out.println(": " + mappings);

        // 关闭客户端连接
        restHighLevelClient.close();

    }

输出

: {course=org.elasticsearch.cluster.metadata.MappingMetadata@a78933ee}

删除索引

@Test
    public void delIndex() throws IOException {
        // 查看索引请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("course");
        // 发送请求取响应
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        // 响应状态
        System.out.println("是否删除成功: " + acknowledged);

        // 关闭客户端连接
        restHighLevelClient.close();

    }

输出

是否删除成功: true

7.3 文档操作

创建文档

创建文档步骤如下

  1. 设置请求对象
  2. 添加参数
  3. 将参数转为json 传到请求对象的source
  4. 客户端发送请求获取响应;
@Autowired
    RestHighLevelClient restHighLevelClient;

    @Test
    public void createDoc() throws IOException {
        // 请求对象
        IndexRequest request = new IndexRequest();
        // 设置 索引 和id
        request.index("course").id("1");
        // 参数
        Course course = new Course();
        course.setName("java");
        course.setPrice(new BigDecimal("1800"));
        course.setDescription("不贵,火爆");
        Gson gson = new Gson();
        String json = gson.toJson(course);
        // 添加文档,格式为JSON
        request.source(json, XContentType.JSON);
        // 发送请求,获取响应对象
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println("结果:" + response.getResult());

    }

输出

结果:CREATED

RESTFUL API查看结果

批量新增文档

    @Test
    public void createDocBulk() throws IOException {
        //创建批量新增请求对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("course").id("2").source(XContentType.JSON, "name", "java"));
        request.add(new IndexRequest().index("course").id("3").source(XContentType.JSON, "name", "python"));
        request.add(new IndexRequest().index("course").id("4").source(XContentType.JSON, "name", "go"));
        //发送请求,获取响应对象
        BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
         System.out.println("结果:" + responses.getTook());

    }

结果

结果:13ms

修改文档

修改文档,指定索引,id,然后只需要将修改的内容放入map,发送请求;

    @Test
    public void updateDoc() throws IOException, JSONException {
        // 请求对象
        UpdateRequest request = new UpdateRequest();
        // 设置 索引 和id
        request.index("course").id("1");
        // 参数
        // 添加文档,格式为JSON
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","python");
        request.doc(map);
        // 发送请求,获取响应对象
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println("结果:" + response.getResult());

    }

结果

结果:UPDATED

查看文档

    @Test
    public void viewDoc() throws IOException {
        //创建请求对象
        GetRequest request = new GetRequest().index("course").id("1");
        //发送请求,获取响应对象
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        System.out.println("结果:"+ response.getSource());

    }

结果

结果:{price=1800, name=python, description=不贵,火爆}

删除文档

    @Test
    public void delDoc() throws IOException {
        //创建请求对象
        DeleteRequest request = new DeleteRequest().index("course").id("1");
        //发送请求,获取响应对象
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());

    }

结果

DELETED

批量删除文档

  @Test
    public void delDocBulk() throws IOException {
        //创建请求对象
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("course").id("2"));
        request.add(new DeleteRequest().index("course").id("3"));
        request.add(new DeleteRequest().index("course").id("4"));
        //发送请求,获取响应对象
        BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println("took:" + responses.getTook());

    }

结果

took:12ms

查询所有文档

执行之前的批量新增操作后执行此步骤

@Test
    public void  selectAll() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("course");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"java"}
------华丽的分割线-----
{"name":"python"}
------华丽的分割线-----
{"name":"go"}
------华丽的分割线-----

匹配查询文档

根所有查询文档基本一样,改变查询条件即可

@Test
    public void  selectMatch() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("course");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询匹配数据
        sourceBuilder.query(QueryBuilders.matchQuery("name","java"));
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"java"}
------华丽的分割线-----

关键字查询

// 关键字查询
    @Test
    public void keySelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("course");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 关键字查询
        sourceBuilder.query(QueryBuilders.termQuery("name","java"));
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

分页查询

 @Test
    public void pageSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("course");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        // 当前页
        sourceBuilder.from(1);
        // 每页显示条
        sourceBuilder.size(1);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"python"}
------华丽的分割线-----

排序查询

排序查询要以关键字keyword类型的字段进行排序

// 排序查询
    @Test
    public void sortSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.sort("address", SortOrder.DESC);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"xuezai","address":"北爱尔兰","date":"2021-04-10 00:00:00","figure":"小识"}
------华丽的分割线-----
{"name":"haixiao","address":"东印度","date":"2021-04-10 00:00:00","figure":"小知"}
------华丽的分割线-----

过滤查询

 // 过滤查询
    @Test
    public void filterSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        // 排除字段
        String[] excludes = {};
        // 包含字段
        String[] includes = {"name", "address"};
        sourceBuilder.fetchSource(includes, excludes);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"address":"东印度","name":"haixiao"}
------华丽的分割线-----
{"address":"北爱尔兰","name":"xuezai"}
------华丽的分割线-----

布尔查询

@Test
    public void boolSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /// 必须包含
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", "haixiao"));
        // 一定不包含
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("figure", "小识"));
        // 可能包含
        boolQueryBuilder.should(QueryBuilders.matchQuery("figure", "小识"));
        // 查询
        sourceBuilder.query(boolQueryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"haixiao","address":"东印度","date":"2021-04-10 00:00:00","figure":"小知"}
------华丽的分割线-----

范围查询

 @Test
    public void rangeSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("date");
        // 大于等于
        rangeQuery.lte("2021-04-12 00:00:00");
        // 小于等于
        rangeQuery.lte("2021-04-13 00:00:00");
        // 查询
        sourceBuilder.query(rangeQuery);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"haixiao","address":"东印度","date":"2021-04-10 00:00:00","figure":"小知"}
------华丽的分割线-----
{"name":"xuezai","address":"北爱尔兰","date":"2021-04-10 00:00:00","figure":"小识"}
------华丽的分割线-----

模糊查询

 @Test
    public void likeSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("figure", "小*");
        // 查询
        sourceBuilder.query(queryBuilder);
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"haixiao","address":"东印度","date":"2021-04-10 00:00:00","figure":"小知"}
------华丽的分割线-----
{"name":"xuezai","address":"北爱尔兰","date":"2021-04-10 00:00:00","figure":"小识"}
------华丽的分割线-----

高亮查询

    @Test
    public void hightLigntSelect() throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("event");
        // 构建请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //高亮查询
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","haixiao");
        //设置查询方式
        sourceBuilder.query(termsQueryBuilder);
        //构建高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置标签前缀
        highlightBuilder.preTags("<font color='red'>");
        //设置标签后缀
        highlightBuilder.postTags("</font>");
        //设置高亮字段
        highlightBuilder.field("name");
        //设置高亮构建对象
        sourceBuilder.highlighter(highlightBuilder);

        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 查询结果
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //输出每条结果信息
            System.out.println(hit.getSourceAsString());
            //打印高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
            System.out.println("------华丽的分割线-----");
        }
    }

输出

{"name":"haixiao","address":"东印度","date":"2021-04-10 00:00:00","figure":"小知"}
{name=[name], fragments[[<font color='red'>haixiao</font>]]}
------华丽的分割线-----

相关文章