Elasticsearch 7.x入门学习-Java API操作

news2024/11/13 16:33:58

1 创建项目

在idea开发工具中创建Maven项目
在这里插入图片描述

修改 pom 文件,增加 Maven 依赖关系

<dependencies>
        <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>
        <!-- elasticsearch 依赖 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.9</version>
        </dependency>
        <!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

新建ClientTest类创建客户端对象测试是否能连接

public class ClientTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        System.out.println(client);
        client.close();
    }
}

备注:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名
执行代码,查看控制台信息,没有报错证明连接成功:
在这里插入图片描述

2 索引操作

通过 Java API 客户端对象对 ES 索引进行操作

2.1 创建索引

public class IndexTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        System.out.println(client);
        // 创建索引 - 请求对象
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("user");
        // 发送请求,获取响应
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        // 获取响应状态
        boolean acknowledged = createIndexResponse.isAcknowledged();
        System.out.println("操作状态 = " + acknowledged);
        client.close();
    }
}

执行结果:
在这里插入图片描述

2.2 查看索引

public class IndexTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 查询索引 - 请求对象
        GetIndexRequest request = new GetIndexRequest("user");
        // 发送请求,获取响应
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        System.out.println("aliases:" + response.getAliases());
        System.out.println("mappings:" + response.getMappings());
        System.out.println("settings:" + response.getSettings());
        client.close();
    }
}

执行结果:
在这里插入图片描述

2.3 删除索引

public class IndexTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
       DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("user");
       // 发送请求,获取响应
       AcknowledgedResponse deleteResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
       System.out.println("操作状态 = " + deleteResponse.isAcknowledged());
       client.close();
    }
}

删除索引执行完成后再次查看索引会报错
在这里插入图片描述

3 文档操作

3.1 新增文档

创建数据模型实体类User

public class User {

    private String name;
    private Integer age;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

创建连接,创建数据添加到文档上,没有索引的话会自动创建索引并添加文档

public class DocumentTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        createDocument(client);
        System.out.println(client);
        client.close();
    }

    private static void createDocument(RestHighLevelClient client) throws IOException {
        // 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();
        // 设置索引及唯一性标识
        request.index("user").id("1001");
        // 创建数据对象
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
        ObjectMapper objectMapper = new ObjectMapper();
        String productJson = objectMapper.writeValueAsString(user);
        // 添加文档数据,数据格式为 JSON 格式
        request.source(productJson, XContentType.JSON);
        // 客户端发送请求,获取响应对象
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        // 打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());
    }
}

执行结果:
在这里插入图片描述

3.2 查询文档

根据id查询文档示例

public class DocumentTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        searchDocument(client);
        client.close();
    }

    private static void searchDocument(RestHighLevelClient client) throws IOException {
        //1.创建请求对象
        GetRequest request = new GetRequest().index("user").id("1001");
        //2.客户端发送请求,获取响应对象
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_type:" + response.getType());
        System.out.println("_id:" + response.getId());
        System.out.println("source:" + response.getSourceAsString());
    }
}

执行结果:
在这里插入图片描述

3.3 修改文档

根据id将sex更新为“女”代码示例:

public class DocumentTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        updateDocument(client);
        client.close();
    }

    private static void searchDocument(RestHighLevelClient client) throws IOException {
        //1.创建请求对象
        GetRequest request = new GetRequest().index("user").id("1001");
        //2.客户端发送请求,获取响应对象
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_type:" + response.getType());
        System.out.println("_id:" + response.getId());
        System.out.println("source:" + response.getSourceAsString());
    }

    private static void updateDocument(RestHighLevelClient client) throws IOException {
        searchDocument(client);
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index("user").id("1001");
        updateRequest.doc(XContentType.JSON, "sex", "女");
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());
        searchDocument(client);
    }
}

执行结果:
在这里插入图片描述

3.4 删除文档

根据id删除文档

public class DocumentTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        deleteDocument(client);
        client.close();
    }

    private static void deleteDocument(RestHighLevelClient client) throws IOException {
        //查看文档
        searchDocument(client);
        //删除文档
        DeleteRequest deleteRequest = new DeleteRequest().index("user").id("1001");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.toString());
        //查看文档
        searchDocument(client);

    }

    private static void searchDocument(RestHighLevelClient client) throws IOException {
        //1.创建请求对象
        GetRequest request = new GetRequest().index("user").id("1001");
        //2.客户端发送请求,获取响应对象
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_type:" + response.getType());
        System.out.println("_id:" + response.getId());
        System.out.println("source:" + response.getSourceAsString());
    }
}

执行结果:
在这里插入图片描述

3.5 批量操作

public class BatchTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //创建批量新增请求对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张三"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "李四"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "王五"));
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        //打印结果信息
        System.out.println("took:" + bulkResponse.getTook());
        System.out.println("items:" + bulkResponse.getItems());
        client.close();
    }
}

执行结果:
在这里插入图片描述

批量删除操作
批量插入文档后再批量删除文档

public class BatchTest {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //创建批量新增请求对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "张三"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "李四"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "王五"));
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        System.out.println("took:" + bulkResponse.getTook());
        System.out.println("items:" + bulkResponse.getItems());

        searchDocument(client);
        BulkRequest deleteRequest = new BulkRequest();
        deleteRequest.add(new DeleteRequest().index("user").id("1001"));
        deleteRequest.add(new DeleteRequest().index("user").id("1002"));
        BulkResponse deleteResponse = client.bulk(deleteRequest, RequestOptions.DEFAULT);
        //打印结果信息
        System.out.println("took:" + deleteResponse.getTook());
        System.out.println("items:" + deleteResponse.getItems());

        searchDocument(client);
        client.close();
    }

    private static void searchDocument(RestHighLevelClient client) throws IOException {
        //1.创建请求对象
        GetRequest getRequest = new GetRequest().index("user").id("1001");
        //2.客户端发送请求,获取响应对象
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + getResponse.getIndex());
        System.out.println("_type:" + getResponse.getType());
        System.out.println("_id:" + getResponse.getId());
        System.out.println("source:" + getResponse.getSourceAsString());
        GetRequest getRequest2 = new GetRequest().index("user").id("1002");
        //2.客户端发送请求,获取响应对象
        GetResponse getResponse2 = client.get(getRequest2, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + getResponse2.getIndex());
        System.out.println("_type:" + getResponse2.getType());
        System.out.println("_id:" + getResponse2.getId());
        System.out.println("source:" + getResponse2.getSourceAsString());
    }
}

执行结果:
在这里插入图片描述

4 高级查询

4.1 请求体查询

4.1.1 查询所有索引数据

查询所有索引数据,代码示例

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        searchAll(client);
        client.close();
    }


    private static void searchAll(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
}

查询结果:
在这里插入图片描述

4.1.2 term查询

term查询,查询条件为关键字,代码示例:

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        termQuery(client);
        client.close();
    }

    private static void termQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        sourceBuilder.query(QueryBuilders.termQuery("age", 30));
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
}

执行结果:
在这里插入图片描述

4.1.3 分页查询
public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        pageQuery(client);
        client.close();
    }
    
    private static void pageQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        // 当前页其实索引(第一条数据的顺序号)
        sourceBuilder.from(2);
        //每页显示多少条
        sourceBuilder.size(2);
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
}

执行结果:在这里插入图片描述

4.1.2 数据排序

数据排序代码示例:

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        sort(client);
        client.close();
    }




    private static void sort(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.sort("age", SortOrder.ASC);
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }

}

执行结果
在这里插入图片描述

4.1.2 过滤字段

代码示例:

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        fetchSource(client);
        client.close();
    }

    private static void fetchSource(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        //查询字段过滤
        String[] excludes = {};
        String[] includes = {"name", "age"};
        sourceBuilder.fetchSource(includes, excludes);

        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
}

执行结果:
在这里插入图片描述

4.1.2 Bool查询
public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/f61e9a465dba47b69caf62250b594da0.png)

        boolQuery(client);
        client.close();
    }

    private static void boolQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询所有数据
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30));
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
        boolQueryBuilder.should(QueryBuilders.matchQuery("set", "男"));
        sourceBuilder.query(boolQueryBuilder);

        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
    }

执行结果:
在这里插入图片描述

4.1.2 范围查询
public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        rangeQuery(client);
        client.close();
    }

    private static void rangeQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        //大于等于
        rangeQuery.gte(30);
        //小于等于
        rangeQuery.lte(40);
        sourceBuilder.query(rangeQuery);

        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }

    }
}

执行结果:
在这里插入图片描述

4.1.2 模糊查询

代码示例:

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        fuzzyQuery(client);
        client.close();
    }

    private static void fuzzyQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder builder = QueryBuilders.fuzzyQuery("name", "zhangsan").fuzziness(Fuzziness.ONE);
        sourceBuilder.query(builder);

        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }

    }
    }

执行结果:
在这里插入图片描述

4.2 高亮查询

代码示例

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        highLightQuery(client);
        client.close();
    }

    private static void highLightQuery(RestHighLevelClient client) throws IOException  {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "zhangsan");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        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 searchResponse = client.search(request, RequestOptions.DEFAULT);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
            //打印高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            System.out.println(highlightFields);
        }

    }
    }

执行结果
在这里插入图片描述

4.3 聚合查询

4.3.1函数使用

代码示例

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

        maxQuery(client);
        client.close();
    }

    private static void maxQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        System.out.println(searchResponse);
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
    }

执行结果:
在这里插入图片描述

分组统计

public class SearchTest {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
//        searchAll(client);
//        termQuery(client);
//        pageQuery(client);
//        sort(client);
//        fetchSource(client);
//        boolQuery(client);
//        rangeQuery(client);
//        fuzzyQuery(client);
//        highLightQuery(client);
//        maxQuery(client);
        groupByQuery(client);
        client.close();
    }


    private static void groupByQuery(RestHighLevelClient client) throws IOException {
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("student");
        //构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
        request.source(sourceBuilder);
        SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        System.out.println(searchResponse.getAggregations().get("age_groupby").getType());
        //查询匹配
        SearchHits hits = searchResponse.getHits();
        System.out.println("took:" + searchResponse.getTook());
        System.out.println("timeout:" + searchResponse.isTimedOut());
        System.out.println("total:" + hits.getTotalHits());
        System.out.println("MaxScore:" + hits.getMaxScore());
        System.out.println("hits========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            System.out.println(hit.getSourceAsString());
        }
    }
    }

在这里插入图片描述

官方Java API 文档地址:
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/getting-started-java.html
代码地址:https://github.com/JustCoding-Hai/es-demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1947187.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2024恶意样本提交激励计划:年中特别回馈惊喜来袭

恶意样本提交激励计划 “恶意样本提交激励计划”由CACTER邮件安全发起&#xff0c;主要目的是更好地帮助客户排查潜在风险问题&#xff0c;同时丰富Coremail邮件安全大数据中心威胁邮件云端特征库&#xff0c;共同提升Coremail邮件安全大数据中心的识别能力&#xff0c;共同建…

别错过!2024年苹果iPhone AI革命:揭秘技术突破与未来蓝图

本文首发于公众号“AntDream”&#xff0c;欢迎微信搜索“AntDream”或扫描文章底部二维码关注&#xff0c;和我一起每天进步一点点 2024年&#xff0c;苹果公司的iPhone手机在技术创新和系统升级方面展现出一系列亮点&#xff0c;预示着苹果在智能手机领域的持续领导地位。以下…

【python】Python中采集Prometheus数据,进行数据分析和可视化展示

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

openEuler安装docker,加速镜像拉取

文章目录 文章来源1.配置镜像源2.编辑配置文件3.安装想要的版本4. ~ 原神&#xff01;5.由于很多镜像无法拉取配置镜像源 文章来源 http://t.csdnimg.cn/zYDYy 原文连接 由于之前的仓库不让用且 1.配置镜像源 由于 国外的镜像仓库好多不让用 所以配置阿里的镜像源 yum-confi…

MySQL之视图和索引

新建数据库 插入数据 处理表 1. 2. 3. mysql> alter table sc add unique index SC_INDEX (sno asc,cno asc); 4. mysql> create view stu_info as select student.sno,ssex,sc.cno,score from student join sc on student.snosc.sno; 5. mysql> drop index S…

VD2120-DB可替代HY2120-DB 两串可充电锂电池保护IC

VD2120系列10,内置高精度电压检测电路和延时电路&#xff0c;是用于2节串联锂离子/锂聚合物可再充电电池的保护IC。VD2120系列IC适合于对2节串联可再充电锂离子/锂聚合物电池的过充电、过放电和过电流进行保护。 VD2120-DB的参数如下 HY2120-DB的参数如下 参数上面的使用上基本…

LeetCode - #103 二叉树的锯齿形层序遍历

文章目录 前言1. 描述2. 示例3. 答案关于我们 前言 我们社区陆续会将顾毅&#xff08;Netflix 增长黑客&#xff0c;《iOS 面试之道》作者&#xff0c;ACE 职业健身教练。&#xff09;的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 LeetCode 算法到目前我们已经更新…

销售分析,奥威BI,销售好帮手

【销售分析&#xff0c;奥威BI&#xff0c;销售好帮手】 在商海浮沉中&#xff0c;销售数据是企业最宝贵的资产之一&#xff0c;它不仅反映了市场的反馈&#xff0c;更是指引企业未来战略方向的灯塔。奥威BI&#xff08;Business Intelligence&#xff09;&#xff0c;作为数据…

【实现100个unity特效之8】使用ShaderGraph实现2d贴图中指定部分局部发光效果

最终效果 寒冰法师 火焰法师 文章目录 最终效果寒冰法师火焰法师 素材一、功能分析实现方法基本思路Unity的Bloom后处理为什么关键部位白色&#xff1f;最终结果 二、 新建URP项目三、合并图片四、使用PS制作黑白图片方法一 手动涂鸦方法二 魔棒工具1. 拖入图片进PS&#xff0…

干货 | 记一次src通杀漏洞挖掘

0x1 前言 这里我是有目的地去对某机构或者某学校进行渗透测试漏洞挖掘的&#xff0c;之前在网上看到很多文章说可以直接去edusrc官网的漏洞排行榜上去找&#xff0c;可以去看一些开发商排行榜以及某些高校大学的排行榜&#xff0c;里面有很多的该公司或者该学校的漏洞提交情况…

PACS医学影像临床信息系统,C#影像归档和通信系统源码,PACS源码,支持图像的获取、传输、浏览、打印、测量、重建、对比、存储、处理,电子胶片影像管理等

医学影像临床信息系统具有图像采集、显示、存储、传输和管理等功能&#xff0c;支持DICOM影像设备和非DICOM影像设备&#xff0c;可以识别CT、MR、CR/DR、X光、DSA、B超、NM、SC等设备的图像类型&#xff0c;可对数字影像进行无损压缩和有损压缩处理。C/S体系结构的多媒体数据库…

mysql面试(四)

前言 本章节有些长&#xff0c;主要的篇幅是介绍缓存页的算法&#xff0c;如何快速的定位哪些是没有用过的&#xff0c;哪些是用过的&#xff0c;哪些是要淘汰掉的。 建议可以阅读一下这里面LRU算法相关的内容&#xff0c;和很多组件里面基本原理都是想通的&#xff0c;比如re…

Mac m1安装 MongoDB 7.0.12

一、下载MongoDB MongoDB 社区版官网下载 二、安装配置MongoDB 1.解压下载的压缩包文件&#xff0c;文件夹重命名为mongodb; 2.将重命名为mongodb的文件夹&#xff0c;放在/usr/local 目录下 3.在/usr/local/mongodb 目录下&#xff0c;新建data 和 log这两个文件夹&#…

【word转pdf】【最新版本jar】Java使用aspose-words实现word文档转pdf

【aspose-words-22.12-jdk17.jar】word文档转pdf 前置工作1、下载依赖2、安装依赖到本地仓库 项目1、配置pom.xml2、配置许可码文件&#xff08;不配置会有水印&#xff09;3、工具类4、效果 踩坑1、pdf乱码2、word中带有图片转换 前置工作 1、下载依赖 通过百度网盘分享的文…

css实现线条中间高亮,左右两边模糊(linear-gradient的运用)

效果&#xff1a; <div class"line"></div> .line {height: 1px;background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, #a9c2ff 50%, rgba(255, 255, 255, 0) 100%);border-radius: 4px 4px 4px 4px; } CSS实现边框底部渐变色的方法:(最简单…

Python基础-语句结构、数据输入

1、分行与缩进 分行&#xff1a; python每一句语句有长度限制&#xff0c;因此不应过长&#xff0c;如果语句过长可以使用\续航符或者加上()控制换行。 []&#xff0c;{}, ()可以直接跨越多行&#xff0c;在列表、字典、元组中需要换行的时候可以不用添加续行符号。 缩进&…

【Java题解】以二进制加法的方式来计算两个内容为二进制数字的字符串相加的结果

&#x1f389;欢迎大家收看&#xff0c;请多多支持&#x1f339; &#x1f970;关注小哇&#xff0c;和我一起成长&#x1f680;个人主页&#x1f680; &#x1f451;目录 分析&#xff1a;&#x1f680; 数字层面分析⭐ 字符串层面分析⭐ 代码及运行结果分析:&#x1f6…

如何在 Windows 11 中录制屏幕

录制屏幕是Windows 11上一项非常有用的功能。在专业方面&#xff0c;它允许您捕获屏幕以突出显示问题或向同事展示新的工作流程。您还可以录制演示文稿&#xff0c;并在整个公司内共享。对于游戏&#xff0c;它可以让您录制动作片段&#xff0c;然后可以与朋友分享或在线发布。…

Vue---vue3+vite项目内使用devtools,快速开发!

背景 我们在前期开发时&#xff0c;一般使用chrome或者edge浏览器&#xff0c;会使用vue-devtools或react-devtools&#xff08;此插件个人未使用&#xff0c;可百度下是否可内嵌入项目&#xff01;&#xff09;来审查vue项目&#xff1b;这个需要安转浏览器插件才可支持&…

Python脚本通过Kvaser和ECU进行CAN通信

1 安装软件 Kvaser官网: https://kvaser.com/download/ 下载下面三个软件包: 下载完如下图: 双击安装这三个软件。 2 查看设备信息 将 Kvaser 工具连接电脑和 ECU,工具包含两个物理通道, CAN I 和 CAN II,我的是用 CAN I 和 ECU 连接的。 然后打开下面的软件, …