Elasticsearch(3)——JavaAPI操作Elasticsearch

Elasticsearch软件是由Java语言开发的,所以也可以通过JavaAPI的方式对Elasticsearch服务进行访问。

ES 官方提供了三种 Java API 接口,分别是 TransportClient、Java Low Level REST Client、 Java High Level REST Client。 其中 TransportClient 在 ES 7.x 版本中被标记为过时,并且将在 ES 8.x 版本中完全移除。 原因是 ES 版本迭代较快,TransportClient 使用了特定的传输协议,如果其版本与 ES 实例版 本不一致则可能导致兼容性问题。ES 官方提供了向后兼容的 Java Low Level REST Client, 并在此基础上提供了功能更多的 J a v a H i g h L e v e l R e s t C l i e n t \textcolor{red}{JavaHighLevelRestClient} JavaHighLevelRestClient ,因此使用 Java High Level REST Clientl来调用Elasticsearch接口。

1 导入依赖


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

<!-- 请求传输 json格式的数据-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>


<!-- Java High Level REST Client-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>


<!-- elasticsearch 底层依赖log4j的-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>
        </dependency>
    </dependencies>

2 索引操作

2.1 创建索引

创建名为post的索引 ,使用CreateIndexRequest,等价于 PUT请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post

public class RestHighLevelClient_IndexCreate {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //判断索引是否已存在
        GetIndexRequest getIndexRequest=new GetIndexRequest(INDEX_NAME);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if(!exists){
            //创建索引的请求 指定索引的名字
            CreateIndexRequest request=new CreateIndexRequest(INDEX_NAME);
            //使用客户端向指定es服务器发送创建索引的请求,获得响应
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            //响应状态
            boolean acknowledged = response.isAcknowledged();

            if(acknowledged){
                System.out.println("创建索引成功");
            }
        }else{
            System.out.println("当前索引已存在");
        }
        //关闭es客户端
        client.close();
    }
}
2.3 查询索引

查询名为post的索引信息,等价于发送Get请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post

public class RestHighLevelClient_IndexSearch {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //获得索引的请求 指定索引的名字
        GetIndexRequest request=new GetIndexRequest(INDEX_NAME);
        //使用客户端向指定es服务器发送查询索引为post的请求的请求,获得响应
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);

        //打印响应结果
        System.out.println(response.getAliases());
        System.out.println(response.getMappings());
        System.out.println(response.getSettings());

        //关闭es客户端
        client.close();
    }
}
2.4 删除索引

删除名为post的索引,等价于发送Delete请求 h t t p : / / l o c a l h o s t : 9200 / p o s t \textcolor{red}{http://localhost:9200/post} http://localhost:9200/post

public class RestHighLevelClient_IndexDelete {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        //判断索引是否已存在
        GetIndexRequest getIndexRequest=new GetIndexRequest(INDEX_NAME);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if(exists){
            DeleteIndexRequest request=new DeleteIndexRequest(INDEX_NAME);
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            if(response.isAcknowledged()){
                System.out.println("成功删除索引");
            }
        }else{
            System.out.println("当前索引不存在,无法删除");
        }

        //关闭es客户端
        client.close();
    }
}

3 文档操作

public class Post {

    /**
     * 文章id
     */
    private  Integer Id;
    /**
     * 文章作者
     */
    private  String author;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 文章标题
     */
    private String title;

    /**
     * 文章内容
     */
    private String content;
 }

文档需要操作的字段信息如上 ,包含文章Id,文章作者、创建时间、文章标题、内容等

3.1 新增文档数据

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        IndexRequest request=new IndexRequest();
        request.index(INDEX_NAME).id("1001");

        //定义需要的插入的文档数据
        Post post=new Post();
        post.setId(3);
        post.setAuthor("LuisTom");
        post.setCreateTime(new Date());
        post.setTitle("自定义字段映射");
        post.setContent("尽管在很多情况下基本字段数据类型已经够用,但你经常需要为单独字段自定义映射,特别是\n" +
                "字符串字段。自定义映射允许你执行下面的操作:\n" +
                "\uF06C 全文字符串字段和精确值字符串字段的区别\n" +
                "\uF06C 使用特定语言分析器\n" +
                "\uF06C 优化字段以适应部分匹配\n" +
                "\uF06C 指定自定义数据格式\n" +
                "\uF06C 还有更多");

        //序列化成json文档
        ObjectMapper mapper=new ObjectMapper();
        String postJson = mapper.writeValueAsString(post);

        //数据传输的post对象序列化成json的内容信息
        request.source(postJson, XContentType.JSON);

        //传输新增文档的响应response
        IndexResponse response= client.index(request,RequestOptions.DEFAULT);
        //打印响应结果
        System.out.println(response.toString());

        //关闭es客户端
        client.close();
    }
}
3.2 查询文档

等价于发送Get请求 h t t p : / / l o c a l h o s t : 9200 / p o s t / d o c / 1001 \textcolor{red}{http://localhost:9200/post/ _doc/1001} http://localhost:9200/post/doc/1001

public class RestHighLevelClient_DocSearch {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        //获得索引post上 id为1001的文档信息
        GetRequest request=new GetRequest(INDEX_NAME,"1001");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String source = response.getSourceAsString();

        System.out.println(response);


        //关闭es客户端
        client.close();
    }
}
3.3 搜索文档

通过SearchSourceBuilder 构建不同的搜索对象,去Index上搜索文档信息

public class RestHighLevelClient_DocQuery {

    //索引名称
    private static final String INDEX_NAME = "post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        SearchRequest request = new SearchRequest(INDEX_NAME);
        //构建查询对象
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //builder.query(QueryBuilders.matchQuery("author","lyf")); //author字段匹配 lyf 使用matchQuery
        //builder.query(QueryBuilders.termQuery("author","lyf")); //author字段匹配 lyf 使用termQuery

       //BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
       //boolQueryBuilder.must(QueryBuilders.matchQuery("author","lyf"))
       //                        .must(QueryBuilders.matchQuery("id","1"));
       //builder.query(boolQueryBuilder); //组合条件查询 BoolQueryBuilder

        //builder.query(QueryBuilders.rangeQuery("id").gte(2).lte(3)); //范围查询,id>=2 and id<=3的文档数据 rangeQuery
        builder.query(QueryBuilders.matchPhraseQuery("title","Elasticsearch")); //模糊查询


        //分页查询 每页两条,查询第一页数据
        //from =(当前页面-1)*size
        builder.from(0);
        builder.size(2);

        //过滤筛选字段
        String[] excludes = {}; //需要排除的字段
        String[] includes = {"id", "title", "author"};//需要筛选的字段
        builder.fetchSource(includes, excludes);
        builder.sort("id", SortOrder.DESC);//根据id倒序排

        //传入查询对象
        request.source(builder);

        //获得查询响应对象
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            //遍历打印查询后的数据
            System.out.println(hit.getSourceAsString());
        }

        //关闭es客户端
        client.close();
    }
}

3.4 删除文档

等价于发送Delete请求 h t t p : / / l o c a l h o s t : 9200 / p o s t / d o c / 1001 \textcolor{red}{http://localhost:9200/post/ _doc/1001} http://localhost:9200/post/doc/1001

public class RestHighLevelClient_DocDelete {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );


        //删除post id为1001的文档的请求
        DeleteRequest request=new DeleteRequest(INDEX_NAME,"1001");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response);


        //关闭es客户端
        client.close();
    }
} 
3.5 批量新增文档
public class RestHighLevelClient_DocBatchAdd {

    //索引名称
    private static  final  String INDEX_NAME="post";

    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        ObjectMapper mapper=new ObjectMapper();

        //定义需要的插入的文档数据
        Post post_1=new Post();
        post_1.setId(1);
        post_1.setAuthor("lyf");
        post_1.setCreateTime(new Date());
        post_1.setTitle("Elasticsearch介绍");
        post_1.setContent("Elasticsearch 是一款高度可伸缩的全文检索和分析引擎。用于近实时存储、搜索和分析大量数\n" +
                "据。在 Elastic APM 中,Elasticsearch 用于存储和聚合性能监控指标。");
        String str_1=mapper.writeValueAsString(post_1);


        Post post_2=new Post();
        post_2.setId(2);
        post_2.setAuthor("lyf");
        post_2.setCreateTime(new Date());
        post_2.setTitle("Mapping");
        post_2.setContent("映射(mapping)就像数据库中的 Schema ,描述了文档可能具有的字段或属性、每个字段的\n" +
                "数据类型,比如 Text,Keyword,Integer 或 Date ,以及 Lucene 是如何索引和存储这些字\n" +
                "段的。");

        String str_2=mapper.writeValueAsString(post_2);

        //批量新增请求
        BulkRequest request=new BulkRequest();
        request.add(new IndexRequest().index(INDEX_NAME).id("1001").source(str_1,XContentType.JSON));
        request.add(new IndexRequest().index(INDEX_NAME).id("1002").source(str_2,XContentType.JSON));
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);


        BulkItemResponse[] items = response.getItems();
        for (BulkItemResponse re:items){
            //遍历打印响应结果信息
            System.out.println(re.toString());
        }


        //关闭es客户端
        client.close();
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
连接 ElasticsearchJava API 主要包括以下几个步骤: 1. 引入 ElasticsearchJava API 依赖 在项目的 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.9.2</version> </dependency> ``` 2. 创建 Elasticsearch 的客户端 在 Java 代码中,通过 RestClient 的静态方法 `RestClient.builder()` 来创建 Elasticsearch 的客户端,示例如下: ``` RestClientBuilder builder = RestClient.builder( new HttpHost("localhost", 9200, "http") ); RestHighLevelClient client = new RestHighLevelClient(builder); ``` 其中,`HttpHost` 为 Elasticsearch 的地址和端口号,可以根据实际情况进行修改。 3. 操作 Elasticsearch 创建客户端之后,就可以使用 ElasticsearchJava API 进行操作了。以下是一些常见的操作示例: - 创建索引: ``` CreateIndexRequest request = new CreateIndexRequest("index_name"); client.indices().create(request, RequestOptions.DEFAULT); ``` - 删除索引: ``` DeleteIndexRequest request = new DeleteIndexRequest("index_name"); client.indices().delete(request, RequestOptions.DEFAULT); ``` - 添加文档: ``` IndexRequest request = new IndexRequest("index_name"); request.id("document_id"); request.source("field1", "value1", "field2", "value2"); IndexResponse response = client.index(request, RequestOptions.DEFAULT); ``` - 获取文档: ``` GetRequest request = new GetRequest("index_name", "document_id"); GetResponse response = client.get(request, RequestOptions.DEFAULT); ``` - 搜索文档: ``` SearchRequest request = new SearchRequest("index_name"); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termQuery("field1", "value1")); request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); ``` 以上仅是 Elasticsearch Java API 的一部分示例,具体的操作可以根据实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值