Elasticsearch入门学习(四):使用javaAPI学习ES

一、Maven依赖

    <!--刚开始少这个包创建索引失败    Validation Failed: 1: type is missing;   官方文档并没有给这个提示-->
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.1.0</version>
    </dependency>

二、开始之前的准备

官方文档

    /**
     * 连接ES
     * @return
     */
    public RestHighLevelClient start() {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.100.151", 9201, "http"),
                        new HttpHost("192.168.100.151", 9202, "http"),
                        new HttpHost("192.168.100.151", 9203, "http")));
        return restHighLevelClient;
    }
 /**
 * 操作所用到的实体类
 */
@Data
class Article{
private long id;
private String title;
    public Article(long id, String title) {
        this.id = id;
        this.title = title;
    }
}

三、关于索引的操作

官方文档

  • 新增索引
  public void createIndex(RestHighLevelClient client) {
        //索引名称
        CreateIndexRequest request = new CreateIndexRequest("hello");
        //分片副本
        request.settings(Settings.builder().put("index.number_of_shards", 5)
                .put("index.number_of_replicas", 1));
        //内容
        Map <String,Object> id = new HashMap <>();
        id.put("type","text");
        id.put("store",true);
        Map <String,Object> title = new HashMap <>();
        title.put("type","text");
        title.put("store",true);
        title.put("index",true);
        title.put("analyzer", "standard");
        Map <String,Object> properties = new HashMap <>();
        properties.put("id",id);
        properties.put("title",title);
        Map <String,Object> mapping = new HashMap <>();
        mapping.put("properties",properties);
        request.mapping(mapping);
        try {
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 查询指定索引
public void getIndex(RestHighLevelClient client) throws IOException {
    //索引名称
    GetIndexRequest request = new GetIndexRequest("hello");
    try {
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 删除索引
public void delIndex(RestHighLevelClient client){
    DeleteIndexRequest request = new DeleteIndexRequest("hello");
    try {
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、关于文档的操作

官方文档

  • 创建文档
    public void createDocument(RestHighLevelClient client){
        //索引名称
        IndexRequest indexRequest = new IndexRequest("hello");
        ObjectMapper mapper = new ObjectMapper();
        Article article = new Article(3L, "web前端");
        byte[] json = new byte[0];
        try {
            json = mapper.writeValueAsBytes(article);
            //可以设置文章ID
            indexRequest.id("5");
            indexRequest.source(json, XContentType.JSON);
            IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 根据文档ID查询文档
public void getDocument(RestHighLevelClient client){
    GetRequest getRequest = new GetRequest("hello", "1");
    GetResponse documentFields = null;
    try {
        documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 更新文档
    public void updateDocument(RestHighLevelClient client){
        UpdateRequest  updateRequest = new UpdateRequest("hello", "1");
        Article article = new Article(2L, "java入门到放弃");
        ObjectMapper mapper = new ObjectMapper();
        byte[] json = new byte[0];
        try {
            json = mapper.writeValueAsBytes(article);
            IndexRequest indexRequest = new IndexRequest("hello");
            indexRequest.source(json, XContentType.JSON);
            updateRequest.doc(indexRequest);
            UpdateResponse updateResponse = client.update(
                    updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 删除文档
    public void delDocument(RestHighLevelClient client){
        DeleteRequest request = new DeleteRequest("hello", "1");
        try {
            DeleteResponse deleteResponse = client.delete(
                    request, RequestOptions.DEFAULT);
            System.out.println(deleteResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 查询文档
    public void searchDocument(RestHighLevelClient client){
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(searchResponse.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

原文地址:https://www.cnblogs.com/yangk1996/p/12657694.html

时间: 2024-08-30 13:38:26

Elasticsearch入门学习(四):使用javaAPI学习ES的相关文章

Elasticsearch入门教程(四):Elasticsearch文档CURD

原文:Elasticsearch入门教程(四):Elasticsearch文档CURD 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/vbirdbest/article/details/79217590 一: 新增文档POST /{index}/{type} 或 PUT /{index}/{type}/{id} 注意:新增文档时可以显式指定id,id可以是数字也可以是字符串,如果不显示指

ElasticSearch入门 第一篇:Windows下安装ElasticSearch

https://www.elastic.co/downloads/past-releases/elasticsearch-2-4-4 这是ElasticSearch 2.4 版本系列的第一篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 ElasticSearch入门 第三篇:索引 ElasticSearch入门 第四篇:使用C#添加和更新文档 ElasticSearch入门 第五篇:使用C#查询文档

ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套

这是ElasticSearch 2.4 版本系列的第六篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 ElasticSearch入门 第三篇:索引 ElasticSearch入门 第四篇:使用C#添加和更新文档 ElasticSearch入门 第五篇:使用C#查询文档 ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套 在ElasticSearch中,使用JSON结构来存储数据,

ElasticSearch入门 第八篇:存储

这是ElasticSearch 2.4 版本系列的第八篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 ElasticSearch入门 第三篇:索引 ElasticSearch入门 第四篇:使用C#添加和更新文档 ElasticSearch入门 第五篇:使用C#查询文档 ElasticSearch入门 第六篇:复合数据类型——数组,对象和嵌套 ElasticSearch入门 第七篇:分析器 Elasti

Elasticsearch入门学习(一):安装ES7.0.1

一.Elasticsearch介绍 之前有学习使用过Solr.Elasticsearch也是基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎.设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便.官方客户端在Java..NET(C#).PHP.Python.Apache Groovy.Ruby和许多其他语言中都

MongoDB入门学习(四):MongoDB的索引

上一篇讲到了MongoDB的基本操作增删查改,对于查询来说,必须按照我们的查询要求去集合中,并将查找到的结果返回,在这个过程中其实是对整个集合中每个文档进行了扫描,如果满足我们的要求就添加到结果集中最后返回.对于小集合来说,这个过程没什么,但是集合中数据很大的时候,进行表扫描是一个非常恐怖的事情,于是有了索引一说,索引是用来加速查询的,相当于书籍的目录,有了目录可以很精准的定位要查找内容的位置,从而减少无谓的查找. 1.索引的类型 创建索引可以是在单个字段上,也可以是在多个字段上,这个根据自己的

Objective C 快速入门学习四

类 1.合成存取器方法 @property   成员变量 @synthesize 成员变量 可以让编译器自动合成 设置和获取函数的方法,不用手动生成set成员变量,Get成员变量 @interface Complex : NSObject { int iReal,iImag; } @property  int iReal, iImag;  //合成存取器方法,第一部:@property标识属性 -(void)print; @end @implementation Complex @synthes

javascript学习之入门(四)

/***@author sinux*@date 2013/9/5*@Content javascript基础入门(四)**/二,对象基础0.作用域   a.常见的编程语言都离不开作用域的概念.作用域实际上就是指属性或变量的适用范围.一般来讲有公有,私有,及受保护的作用域之分.   b.实际上,javascript中的所有属性和方法均为公有作用域,没有私有和保护作用域的,显然在js中大谈作用域,除了加深对编程语言的横向比较意识之外,我看不到有什么亮点.   c.虽然js没有静态作用域,不够它可以给

Elasticsearch入门学习(三):集群的搭建

一.集群的一些概念 集群 一个集群cluster由一个或者多个节点组成,具有相同的cluster.name,协同工作,分项数据和负载.当有新的节点加入或者删除了一个节点时,集群回感知到并能够平衡数据.ElasticSearch中可以监控很多信息,有一个最重要的就是集群健康.集群健康有三个状态:green(所有主要分片和复制分片都可用),yellow(所有主要分片可用,但不是所有复制分片都可用),red(不是所有的主要分片都可用). 节点 一个节点node就是一个ElasticSearch的实例.

AI - 深度学习入门十四章- 摘要1

原文链接:https://yq.aliyun.com/topic/111 01 - 一入侯门"深"似海,深度学习深几许 什么是"学习"? "如果一个系统,能够通过执行某个过程,就此改进了它的性能,那么这个过程就是学习". 学习的核心目的,就是改善性能. 什么是机器学习? 定义1: 对于计算机系统而言,通过运用数据及某种特定的方法(比如统计的方法或推理的方法),来提升机器系统的性能,就是机器学习. 定义2: 对于某类任务(Task,简称T)和某项性