Elasticsearch(3)——JavaAPI操作Elasticsearch

这篇具有很好参考价值的文章主要介绍了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文章来源地址https://www.toymoban.com/news/detail-544534.html

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();
    }
}

到了这里,关于Elasticsearch(3)——JavaAPI操作Elasticsearch的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring整合Elasticsearch----其他Elasticsearch操作支持

    本文介绍了对Elasticsearch操作的额外支持,这些操作无法通过存储库接口直接访问。建议将这些操作添加为自定义实现,如“ 自定义存储库实现”中所述。 当使用Spring Data创建Elasticsearch索引时,可以使用@Setting注解定义不同的索引设置。以下参数可用: useServerConfiguration 不发

    2024年04月13日
    浏览(38)
  • Elasticsearch(1)——倒排索引与HTTP操作Elasticsearch

    1 前言 Elastic Stack 核心产品包括 Elasticsearch【存储数据】、Kibana【展示数据】、Beats 和 Logstash【收集与传输数据】(也称为 ELK Stack)等等。能够安全可靠地从任何来源获取任何格式的数据,然后对数据进行搜索、分析和可视化。sa Elasticsearch 是一个分布式、RESTful 风格的搜索和

    2024年02月12日
    浏览(34)
  • JavaAPI操作Hive

    提示:以下是本篇文章正文内容 启动好Hadoop集群,已安装hive。 接下来启动hive。 启动元数据MetaStore 启动HiveServer服务 我自己启动的是HiveServer2服务, hiveserver默认端口是10000,之后的url填写的端口号就是这个。 hiveserver和hiveserver2的区别: 启动服务不一样 驱动名不一样 url不一

    2024年02月03日
    浏览(20)
  • Zookeeper-JavaApI操作

    Curator 是 Apache ZooKeeper 的Java客户端库。 常见的ZooKeeper Java API : 原生Java API ZkClient Curator Curator 项目的目标是简化 ZooKeeper 客户端的使用。 Curator 最初是 Netfix 研发的,后来捐献了 Apache 基金会,目前是 Apache 的顶级项目。 官网:http://curator.apache.org/ a) 建立连接与CRUD基本操作 Cura

    2024年02月07日
    浏览(32)
  • ES-JavaAPI操作

    Elasticsearch 是一个开源的分布式搜索和分析引擎,可以快速实时地存储、搜索和分析海量数据。它提供了 HTTP RESTful API 供开发者使用,也有 Java 等多种语言的客户端库,方便开发者进行数据的增删改查操作。 本篇文章将围绕 ES-JavaAPI 展开,详细介绍如何使用 Java 操作 Elastics

    2024年02月06日
    浏览(26)
  • 【ElasticSearch】spring-data方式操作elasticsearch(一)

    1.添加依赖 2.添加ES配置 3.添加实体类 4.添加repository 准备操作都做完了,开始进行对elasticsearch操作了,新增一些测试模拟数据 结果: 类似SQL: 可以按照多个字段进行排序 public static Sort by(Order… orders) ; 类似SQL: 类似SQL: 结果: 类似SQL: 结果: 若是查询中文,需要添加 key

    2024年02月04日
    浏览(37)
  • ES基本操作(JavaAPI篇)

    引入jar包依赖 对于其他的查询,需要修改 “QueryBuilders.matchAllQuery()” 注意:中文自动分词,可模糊搜索。如:

    2024年02月16日
    浏览(33)
  • java操作ElasticSearch之批量操作

    出现: 版本冲突、文档类型不对、JAR包与使用的API不一致或其他问题。都可参考以下连接。 ElasticSearch超级实用API描述 以上代码需要变动一下,将一些参数替换掉。

    2024年02月16日
    浏览(43)
  • Elasticsearch基本操作之文档操作

    本文来说下Elasticsearch基本操作之文档操作 文档概述 在创建好索引的基础上来创建文档,并添加数据。 这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式。 在 apifox 中,向 ES 服务器发 POST 请求 :http://localhost:9200/person/_doc,请求体内容为: 服务器响

    2024年02月01日
    浏览(36)
  • docker创建elasticsearch、elasticsearch-head部署及简单操作

    1  拉取elasticsearch镜像      docker pull elasticsearch:7.7.0 2   创建文件映射路径      mkdir /mydata/elasticsearch/data      mkdir /mydata/elasticsearch/plugins      mkdir /mydata/elasticsearch/config 3  文件夹授权         chmod 777 /mydata/elasticsearch/data 4  修改配置文件     cd /mydata/elasticsearch/config  

    2024年02月07日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包