springboot整合elasticsearch之javahighlevelrestclient(代码片段)

ClinEvol ClinEvol     2023-03-21     661

关键词:

1 搭建SpringBoot工程

2 引入ElasticSearch相关坐标。

<properties>
    		<!--一定重新定义版本   版本号一定要和您所安装的ES版本号一致-->
        <elasticsearch.version>7.4.0</elasticsearch.version>
</properties>
<dependencies>
    <!--引入es的坐标-->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.4.0</version>
    </dependency>
    ................

3 编写核心配置类

编写核心配置文件:

这里可以不写在配置,可以直接写在代码中,只是一般都是写在配置文件中

#这个是我们自写的,如果看有es提示,不要用
elasticsearch:
  host: 192.168.126.20   
  port: 9200

编写核心配置类

@Configuration
@ConfigurationProperties(prefix="elasticsearch")
public class ElasticSearchConfig 

    private String host;
    private int port;

    @Bean
    public RestHighLevelClient client()
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host,port,"http")
        ));
      
    
    public String getHost() 
        return host;
    

    public void setHost(String host) 
        this.host = host;
    

    public int getPort() 
        return port;
    

    public void setPort(int port) 
        this.port = port;
    

4 测试客户端对象

记得把maven的单元测试关了

注意:使用@Autowired注入RestHighLevelClient 如果报红线,则是因为配置类所在的包和测试类所在的包,包名不一致造成的

@SpringBootTest
class SpringElasticsearchApplicationTests 

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    void contextLoads() 
        System.out.println(restHighLevelClient);
    

(二)操作ElasticSearch

操作索引要索引的对象来进行操作

//获取索引对象     这个对象提供操作索引的方法
IndicesClient indices = client.indices();
//添加索引对象    RequestOptions.DEFAULT默认的动作
indices.create(new CreateIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//查询索引对象
indices.get(new GetIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//删除索引对象
indices.delete(new DeleteIndexRequest("offcn_index3"),RequestOptions.DEFAULT);

1 添加索引

/**
 * 添加索引:
 * @throws Exception
 */
@Test
   public void addindex() throws IOException 
       // 获取索引对象
       IndicesClient indices = client.indices();
       //create()  CreateIndexRequest("索引名称")    RequestOptions.DEFAULT默的行为
       CreateIndexResponse indexResponse = indices.create(new CreateIndexRequest("student123"), RequestOptions.DEFAULT);
       System.out.println(indexResponse.isAcknowledged());
   

2 添加索引,并添加映射

/**
  * 创建索引并且添加映射
  * @throws IOException
  */
@Test
public void addIndexAndMapping() throws IOException 
    //1.使用client获取操作索引的对象
    IndicesClient indicesClient = restHighLevelClient.indices();
    //2.具体操作,获取返回值
    CreateIndexRequest createRequest = new CreateIndexRequest("offcn");
    //2.1 设置mappings
    String mapping = "\\n" +
        "      \\"properties\\" : \\n" +
        "        \\"address\\" : \\n" +
        "          \\"type\\" : \\"text\\",\\n" +
        "          \\"analyzer\\" : \\"ik_max_word\\"\\n" +
        "        ,\\n" +
        "        \\"age\\" : \\n" +
        "          \\"type\\" : \\"long\\"\\n" +
        "        ,\\n" +
        "        \\"name\\" : \\n" +
        "          \\"type\\" : \\"keyword\\"\\n" +
        "        \\n" +
        "      \\n" +
        "    ";
    createRequest.mapping(mapping, XContentType.JSON);
    //2.2执行创建,返回对象
    CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
    //3.根据返回值判断结果
    System.out.println(response.isAcknowledged());

3 查询、删除、判断索引

3.1 查询索引

/**
  * 查询索引
  */
@Test
public void queryIndex() throws IOException 
    //1:使用client获取操作索引的对象
    IndicesClient indices = restHighLevelClient.indices();
    //2:获得对象,执行具体的操作
    //2.1 创建获取索引的请求对象,设置索引名称
    GetIndexRequest getReqeust = new GetIndexRequest("offcn");
    //2.2 执行查询,获得返回值
    GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
    //3:获取结果,遍历
    Map<String, MappingMetaData> mappings = response.getMappings();
    for (String key : mappings.keySet()) 
        System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
    
  

3.2 删除索引

/**
  * 删除索引
  */
@Test
public void deleteIndex() throws IOException 
    IndicesClient indices = restHighLevelClient.indices();
    DeleteIndexRequest deleteRequest = new DeleteIndexRequest("offcn");
    AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.isAcknowledged());

3.3 索引是否存在

/**
  * 判断索引是否存在
  */
@Test
    public void getIndex() throws IOException 
        IndicesClient indices = client.indices();
        GetIndexRequest student0517 = new GetIndexRequest("student0517");
        boolean exists = indices.exists(student0517, RequestOptions.DEFAULT);
        if(exists)
            GetIndexResponse indexResponse = indices.get(student0517, RequestOptions.DEFAULT);
            Map<String, MappingMetaData> mappings = indexResponse.getMappings();
            System.out.println(mappings);
        else
            System.out.println("索引不存在");
        
    

4 操作文档

4.1 添加文档

添加文档,使用map作为数据

/**
  * 添加文档,使用map作为数据
  */
@Test
public void addDoc() throws IOException 
    //数据对象,map   key要与映射属性对应
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "马同志");
    data.put("age", 20);

    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getResult());

添加文档,使用对象作为数据

添加依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

创建实体类,属性名与映射字段名对应

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student 
    private String brand;
    private Integer price;
    private String title;




  "sutdent78" : 
    "mappings" : 
      "properties" : 
        "brand" : 
          "type" : "keyword"
        ,
        "price" : 
          "type" : "integer"
        ,
        "title" : 
          "type" : "text",
          "analyzer" : "ik_max_word"
        
      
    
  

/**
  * 添加文档,使用对象作为数据
  */
@Test
public void addDoc2() throws IOException 
    //数据对象,javaObject
    Student student=new Student("kaka",22,"南沙中公教育");

    //将对象转为json
    String data = JSON.toJSONString(p);
    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id(p.getId()).source(data, XContentType.JSON);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getId());

4.2 修改文档:添加文档时,如果id存在则修改,id不存在则添加

/**
  * 修改文档:添加文档时,如果id存在则修改,id不存在则添加
  */
@Test
public void updateDoc() throws IOException 
    //数据对象,map
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "朱同志");
    data.put("age", 20);

    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getId());

4.3 根据id查询文档

    @Test
    public void getDoc() throws IOException 
        GetRequest getRequest = new GetRequest("sutdent78").id("1002");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        //集合方式
        Map<String, Object> source = documentFields.getSource();
        for (String key : source.keySet()) 
            System.out.println(source.get(key));
        
        //字符串  -----JSON
        String sourceAsString = documentFields.getSourceAsString();
        System.out.println(sourceAsString);
        //把JSON转换为 stuent
        //JSON字符串-->JSON对象
        JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
        //JSON对象-->Java对象
        Student student = JSONObject.toJavaObject(jsonObject, Student.class);
        System.out.println(student);

    

4.4 根据id删除文档

/**
  * 根据id删除文档
  */
@Test
public void delDoc() throws IOException 
    DeleteRequest deleteRequest = new DeleteRequest("offcn", "1");
    DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.getId());

总结:

//添加、修改   第一个:索引名称   第二个是文档id     第三个是文档内容
restHighLevelClient
    .index( new IndexRequest("offcn_index2").id("as1122").source(data),RequestOptions.DEFAULT)
//查询    第一个参数是索引名称   第二个是文档id
restHighLevelClient.get( new GetRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
//删除    第一个参数是索引名称   第二个是文档id
restHighLevelClient.delete( new DeleteRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)

(三)ElasticSearch的文档批量操作

1 bulk文档 批量操作脚本实现

需求:同时完成【删除,更新,添加】操作 这里的JSON格式不能格式化

POST _bulk
"delete":"_index":"person1","_id":"4"
"create":"_index":"person1","_id":"5"
"name":"八号","age":18,"address":"北京"
"update":"_index":"person1","_id":"2"
"doc":"name":"2号"

查询运行结果~ 

2 bulk批量操作JavaAPI 实现

/**
     *  Bulk 批量操作
     */
    @Test
    public void test2() throws IOException 

        //创建bulkrequest对象,整合所有操作
        BulkRequest bulkRequest =new BulkRequest();

           /*
        # 1. 删除5号记录
        # 2. 添加6号记录
        # 3. 修改3号记录 名称为 “三号”
         */
        //添加对应操作
        //1. 删除5号记录
        DeleteRequest deleteRequest=new DeleteRequest("person1","5");
        bulkRequest.add(deleteRequest);

        //2. 添加6号记录
        Map<String, Object> map=new HashMap<>();
        map.put("name","六号");
        IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
        bulkRequest.add(indexRequest);
        //3. 修改3号记录 名称为 “三号”
        Map<String, Object> mapUpdate=new HashMap<>();
        mapUpdate.put("name","三号");
        UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);

        bulkRequest.add(updateRequest);
        //执行批量操作

        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status()查看详情  

elasticsearch学习springboot整合elasticsearch的原生方式

前面我们已经介绍了springboot整合Elasticsearch的jpa方式,这种方式虽然简便,但是依旧无法解决我们较为复杂的业务,所以原生的实现方式学习能够解决这些问题,而原生的学习方式也是Elasticsearch聚合操作的一个基础。一、修改spr... 查看详情

springboot整合elasticsearch

1引入jar包  <!--elasticsearch--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency&g 查看详情

springboot整合elasticsearch实现多版本的兼容

...最火的搜索引擎ElastiSearch,并和SpringBoot进行结合使用。ElasticSearch介绍ElasticSearch是一个基于Lucene的搜索服务器,其实就是对Lucene进行封装,提供了RESTAPI的操作接口ElasticSearch 查看详情

springboot整合elasticsearch和mysql附案例源码

导读  前二天,写了一篇ElasticSearch7.8.1从入门到精通的(点我直达),但是还没有整合到SpringBoot中,下面演示将ElasticSearch和mysql整合到SpringBoot中,附演示源码。项目介绍模仿NBA网站网址地址:点我直达 接口开发将数据库... 查看详情

[elasticsearch]springboot整合elasticsearch(代码片段)

此文演示在IDEA下,SpringBoot整合ElasticSearch的整体流程,供大伙儿学习测试1.IDEA下选择新建Module2.选择版本3.选择版本+自定义名称4.选择需要的依赖(这里打钩的都选上即可)5.自定义名称、路径6.Pom.xml中把ES版本... 查看详情

springboot整合elasticsearch,实现functionscorequery权重分查询

运行环境:JDK7或8,Maven3.0+技术栈:SpringBoot1.5+,ElasticSearch2.3.2本文提纲一、ES的使用场景二、运行 springboot-elasticsearch 工程三、springboot-elasticsearch 工程代码详解 推荐-「springboot-learning-example」开源项目,Fork一下 查看详情

springboot整合elasticsearch7

SpringBoot连接ElasticSearch有以下种方式,TransportClient,9300端口,在7.x中已经被弃用,据说在8.x中将完全删除restClient,9200端口,highlevelclient,新推出的连接方式,基于restClient。使用的版本需要保持和ES服务端的版本一致。Springboot2... 查看详情

springboot与elasticsearch整合

资源下载:ElasticSearch官方下载地址:https://www.elastic.co/downloads/elasticsearchcurl下载地址:http://curl.haxx.se/download.htmlKibana下载地址:https://www.elastic.co/guide/en/kibana/4.6/index.htmlsense下载地址:https://downl 查看详情

springboot与elasticsearch整合

资源下载:ElasticSearch官方下载地址:https://www.elastic.co/downloads/elasticsearchcurl下载地址:http://curl.haxx.se/download.htmlKibana下载地址:https://www.elastic.co/guide/en/kibana/4.6/index.htmlsense下载地址:https://downl 查看详情

springboot整合elasticsearch(代码片段)

第一、安装Elasticsearch请移步 本文Elasticsearch版本:6.4.2第二、项目操作     <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</arti 查看详情

elasticsearch整合springboot案例

 1、elasticsearch官方文档的使用与介绍1.1、Rest客户端初始化官方文档链接:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html#java-rest-high-getting-sta 查看详情

springboot整合elasticsearch遇到的错误

ErrorstartingApplicationContext.Todisplaytheauto-configurationreportre-runyourapplicationwith‘debug‘enabled.2018-12-2911:54:39.572ERROR7563---[main]o.s.boot.SpringApplication:Applicationstartupfailedo 查看详情

springboot整合elasticsearch框架

新建SpringBoot项目:修改pom.xml文件,引入spring-boot-data-elasticsearchJar包:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</ar 查看详情

springboot整合elasticsearch(windows版)

导言:               elasticsearch是现在很多公司都在用的一个搜索框架,现在的公司一直在用,但是是集成在ssm框架里面的。最近在学习springBoot的时候发现,springBoot可以对elasticsearch进行很好的支持,... 查看详情

springboot整合elasticsearch(windows版)

导言:               elasticsearch是现在很多公司都在用的一个搜索框架,现在的公司一直在用,但是是集成在ssm框架里面的。最近在学习springBoot的时候发现,springBoot可以对elasticsearch进行很好的支持,... 查看详情

springboot整合elasticsearch实现增删改查基本示例

参考技术AElasticSearch被命名为大数据搜索引擎,在文件检索、数据存储方面具有天然的优势。而SpringBoot作为服务整合中间件,在服务组装方面是一款万能粘合器,本文主要提供SpringBoot整合ElasticSearch基本增删改示例。ElasticSearch安... 查看详情

springboot整合elasticsearch(代码片段)

springboot项目导入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional> 查看详情