elasticsearch学习二-javaAPI

1 获取client&对象解析方法

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

    private static List<User> parseUser(SearchHits hits) {
        List<User> userList = new ArrayList<>();
        for (SearchHit hit : hits) {
            User user = JSON.parseObject(hit.getSourceAsString(), User.class);
            user.setHighLight(hit.getHighlightFields());
            userList.add(user);
        }
        return userList;
    }

2 索引操作

2.1 创建索引

    /**
     * 创建索引
     *
     * @param index
     * @return
     * @throws IOException
     */
    public static boolean createIndex(String index) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        return client.indices().create(request, RequestOptions.DEFAULT).isAcknowledged();
    }

2.2 查询索引

    /**
     * 查询索引
     *
     * @param index
     * @return
     * @throws IOException
     */
    public static GetIndexResponse listIndex(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        return client.indices().get(request, RequestOptions.DEFAULT);
    }

2.3 删除索引

    /**
     * 删除索引
     *
     * @param index
     * @return
     * @throws IOException
     */
    public static boolean deleteIndex(String index) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        return client.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged();
    }

3 文档操作

3.1 添加文档

    /**
     * 添加用户
     *
     * @param user
     * @return
     * @throws IOException
     */
    public static IndexResponse addUser(User user) throws IOException {
        IndexRequest request = new IndexRequest().index("user").id(String.valueOf(user.getId()))
                .source(JSON.toJSONString(user), XContentType.JSON);
        return client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 批量添加
     *
     * @param userList
     * @return
     * @throws IOException
     */
    public static BulkResponse batchAddUser(List<User> userList) throws IOException {
        BulkRequest request = new BulkRequest();
        for (User user : userList) {
            request.add(new IndexRequest().index("user").id(String.valueOf(user.getId()))
                    .source(JSON.toJSONString(user), XContentType.JSON));
        }
        return client.bulk(request, RequestOptions.DEFAULT);
    }

3.2 更新文档

    /**
     * 更新用户
     *
     * @param user
     * @return
     * @throws IOException
     */
    public static UpdateResponse updateUser(User user) throws IOException {
        UpdateRequest request = new UpdateRequest().index("user").id(String.valueOf(user.getId()))
                .doc(JSON.toJSONString(user), XContentType.JSON);
        return client.update(request, RequestOptions.DEFAULT);
    }

3.3 根据id获取文档

    /**
     * 根据id获取
     *
     * @param id
     * @return
     * @throws IOException
     */
    public static User getUser(Long id) throws IOException {
        GetRequest request = new GetRequest().index("user").id(String.valueOf(id));
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        return response.isExists() ? JSON.parseObject(response.getSourceAsString(), User.class) : null;
    }

3.4 删除文档

    /**
     * 删除用户
     *
     * @param id
     * @return
     * @throws IOException
     */

    public static DeleteResponse deleteUser(Long id) throws IOException {
        DeleteRequest request = new DeleteRequest().index("user").id(String.valueOf(id));
        return client.delete(request, RequestOptions.DEFAULT);
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     * @throws IOException
     */
    public static BulkResponse batchDelUser(List<Long> idList) throws IOException {
        BulkRequest request = new BulkRequest();
        for (Long id : idList) {
            request.add(new DeleteRequest().index("user").id(String.valueOf(id)));
        }
        return client.bulk(request, RequestOptions.DEFAULT);
    }

4 复杂查询

4.1 全量查询

    /**
     * 查找用户
     *
     * @return
     * @throws IOException
     */
    public static List<User> listUser() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 获取个数
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        // 获取耗时
        TimeValue took = response.getTook();
        System.out.println(took);
        return parseUser(hits);
    }

4.2 条件查询

    /**
     * 根据年龄查询
     *
     * @param age
     * @return
     * @throws IOException
     */
    public static List<User> listUserByAge(int age) throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", age)));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.3 分页排序

    /**
     * 分页排序查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws IOException
     */
    public static PageVO<User> listUserPage(int pageNum, int pageSize) throws IOException {
        int from = (pageNum - 1) * pageSize;
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.from(from);
        builder.size(pageSize);
        // 按照年龄降序
        builder.sort("age", SortOrder.DESC);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        PageVO<User> pageVO = new PageVO<>();
        SearchHits hits = response.getHits();
        pageVO.setData(parseUser(hits));
        pageVO.setRowCount(hits.getTotalHits().value);
        pageVO.setPageCount((pageVO.getRowCount() - 1) / pageSize + 1);
        return pageVO;
    }

4.4 字段过滤

    /**
     * 字段过滤
     *
     * @return
     * @throws IOException
     */
    public static List<User> listUserNameAndAge() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        String[] include = {"name", "age"};
        String[] exclude = {};
        builder.fetchSource(include, exclude);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.5 组合查询

    /**
     * 组合查询
     *
     * @return
     * @throws IOException
     */
    public static List<User> listConditionUser() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 查询21岁并且名字是汤姆的用户
        //boolQueryBuilder.must(QueryBuilders.matchQuery("name", "汤姆"));
        //boolQueryBuilder.must(QueryBuilders.matchQuery("age", "21"));
        // 查询年龄是30或40的用户
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
        boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));
        builder.query(boolQueryBuilder);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.6 范围查询

    /**
     * 范围查询
     *
     * @return
     * @throws IOException
     */
    public static List<User> listRangeUser() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        // 查询30(包含)-50(不包含)之间的用户
        rangeQuery.gte(30);
        rangeQuery.lt(50);
        builder.query(rangeQuery);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.7 模糊查询

    public static List<User> fuzzyQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.fuzzyQuery("name", "汤").fuzziness(Fuzziness.TWO));
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.8 高亮查询

    /**
     * 高亮查询
     *
     * @return
     * @throws IOException
     */
    public static List<User> highlightQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");

        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 设置高亮字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");
        builder.highlighter(highlightBuilder);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        return parseUser(hits);
    }

4.9 聚合查询

    /**
     * 聚合查询,查询年龄最大的用户
     * @throws IOException
     */
    public static void aggQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        ParsedMax max = (ParsedMax) response.getAggregations().asList().get(0);
        System.out.println(max.getName() + ":" + max.getValue());
    }

4.10 分组查询

    /**
     * 分组查询,按照年龄分组统计
     */
    public static void groupQuery() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("user");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age");
        builder.aggregation(aggregationBuilder);
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        ParsedLongTerms terms = (ParsedLongTerms) response.getAggregations().asList().get(0);
        terms.getBuckets().forEach(bucket -> System.out.println(bucket.getKey().toString() + " " + bucket.getDocCount()));
        System.out.println(response);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值