springboot初试elasticsearch

这篇具有很好参考价值的文章主要介绍了springboot初试elasticsearch。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

引入依赖

 elasticsearch的依赖版本与你elasticsearch要一致

<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

索引库的操作 

创建索引库

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class HotelIndexTest {
    // 创建索引语句
    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"starName\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
    private RestHighLevelClient client;
    // 创建索引库
    @Test
    void createHotelIndex() throws IOException {
       
        // 1.创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.准备请求的参数:DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        // 3.发送请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }
    // 初始化连接
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://43.139.59.28:9200")
        ));
    }
    // 关闭连接
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

查看索引库

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端

删除索引库

@Test
    void testDeleteHotelIndex() throws IOException {
        // 1.创建Request对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        // 2.发送请求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

 查看索引库

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端

文档的操作 

数据库实体类

数据库查询后的结果是一个Hotel类型的对象  

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("tb_hotel")
public class Hotel {
    @TableId(type = IdType.INPUT)
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String longitude;
    private String latitude;
    private String pic;
}

 文档实体类

索引库查询后的结果是一个HotelDoc类型的对象,与Hotel不同在于横纵坐标的处理.

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        // 合并横纵坐标
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}

新增文档

 @Resource
    private HotelService hotelService;
    
    @Test
    void testAddDocument() throws IOException {
        // 1.根据id查询酒店数据
        Hotel hotel = hotelService.getById(61083L);
        // 2.转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 3.将HotelDoc转json
        String json = JSON.toJSONString(hotelDoc);

        // 1.准备Request对象
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        // 2.准备Json文档
        request.source(json, XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

查询文档

@Test
    void testGetDocumentById() throws IOException {
        // 1.准备Request
        GetRequest request = new GetRequest("hotel", "61083");
        // 2.发送请求,得到响应
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析响应结果
        String json = response.getSourceAsString();

        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println(hotelDoc);
    }

 结果

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端

修改文档

修改我们讲过两种方式:

  • 全量修改:本质是先根据id删除,再新增

  • 增量修改:修改文档中的指定字段值  

在RestClient的API中,全量修改与新增的API完全一致,这里不再赘述,我们主要关注增量修改  

@Test
    void testUpdateDocument() throws IOException {
        // 1.准备Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        // 2.准备请求参数
        request.doc(
                "price", "952",
                "starName", "四钻"
        );
        // 3.发送请求
        client.update(request, RequestOptions.DEFAULT);
    }

查看文档

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端

删除文档

@Test
    void testDeleteDocument() throws IOException {
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

 查询61083文档

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端

批量导入文档

利用BulkRequest批量将数据库数据导入到索引库中

@Test
    void testBulkRequest() throws IOException {
        // 批量查询酒店数据
        List<Hotel> hotels = hotelService.list();

        // 1.创建Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数,添加多个新增的Request
        for (Hotel hotel : hotels) {
            // 2.1.转换为文档类型HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 2.2.创建新增文档的Request对象
            request.add(new IndexRequest("hotel")
                    .id(hotelDoc.getId().toString())
                    .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
        }
        // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }

查看所有文档

 @Test
    void testMatchAll() throws IOException {
        // 1.准备Request
        SearchRequest request = new SearchRequest("hotel");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.matchAllQuery());
        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 4.解析响应
        System.out.println(response);
    }

结果

springboot初试elasticsearch,elasticsearch,spring boot,elasticsearch,后端文章来源地址https://www.toymoban.com/news/detail-699779.html

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

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

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

相关文章

  • Spring Boot 集成 ElasticSearch

    首先创建一个项目,在项目中加入 ES 相关依赖,具体依赖如下所示: 在配置文件 application.properties 中配置 ES 的相关参数,具体内容如下: 其中指定了 ES 的 host 和端口以及超时时间的设置,另外我们的 ES 没有添加任何的安全认证,因此 username 和 password 就没有设置。 然后在

    2024年02月03日
    浏览(45)
  • Spring Boot 整合Elasticsearch入门

    Spring Data Elasticsearch 是 Spring Data 项目的子项目,提供了 Elasticsearch 与 Spring 的集成。实现了 Spring Data Repository 风格的 Elasticsearch 文档交互风格,让你轻松进行 Elasticsearch 客户端开发。 应粉丝要求特地将 Elasticsearch 整合到 Spring Boot  中去。本来打算整合到 kono 脚手架中,但是转

    2024年04月13日
    浏览(35)
  • Spring Boot 集成 Elasticsearch 实战

    @Configuration public class ElasticsearchConfiguration { @Value(“${elasticsearch.host}”) private String host; @Value(“${elasticsearch.port}”) private int port; @Value(“${elasticsearch.connTimeout}”) private int connTimeout; @Value(“${elasticsearch.socketTimeout}”) private int socketTimeout; @Value(“${elasticsearch.connectionRequestTimeout}”

    2024年04月10日
    浏览(40)
  • Spring Boot集成Elasticsearch实战

    最近项目中要使用Elasticsearch所以就去简单的学习了一下怎么使用,具体的一些在高级的功能暂时展示不了,能力目前有点限,不过一些基本的需求还是可以满足的。所以就写了一篇整理一下也希望能够指出不足之处 docker部署 正常部署 首先根据spring提供的findAll方法获取所有

    2024年02月09日
    浏览(36)
  • Spring boot简单集成Elasticsearch

    本文主要介绍Spring boot如何简单集成Elasticsearch,关于es,可以理解为一个数据库,往es中插入数据,然后使用es进行检索。 环境准备 安装es 和kibana :参考 安装ik分词器:参考 相关配置 pom.xml文件中引入es: yml文件配置es: ES查询 往es插数据 需要让mapper层继承ElasticsearchReposito

    2024年02月22日
    浏览(35)
  • Spring Boot中的Elasticsearch自动配置

    Elasticsearch是一个基于Lucene的分布式全文搜索引擎,它在搜索、分析等方面具有出色的表现。Spring Boot中的Elasticsearch自动配置为我们提供了一种快速集成Elasticsearch的方式,使我们可以在Spring Boot应用程序中轻松地使用Elasticsearch。 本文将介绍Spring Boot中的Elasticsearch自动配置的作

    2024年02月12日
    浏览(35)
  • Spring Boot进阶(19):探索ElasticSearch:如何利用Spring Boot轻松实现高效数据搜索与分析

            ElasticSearch是一款基于Lucene的开源搜索引擎,具有高效、可扩展、分布式的特点,可用于全文搜索、日志分析、数据挖掘等场景。Spring Boot作为目前最流行的微服务框架之一,也提供了对ElasticSearch的支持。本篇文章将介绍如何在Spring Boot项目中整合ElasticSearch,并展

    2024年02月11日
    浏览(44)
  • Spring Boot整合Elasticsearch超详细教程

    SpringBoot整合Elasticsearch超详细教程 最新高级版 (1)导入springboot整合ES高级别客户端的坐标 (2)使用编程的形式设置连接的ES服务器,并获取客户端对象 (3)Book实体类 (4)连接Dao层 (5)使用客户端对象操作ES 例如创建索引:(这里需要先执行上面的删除索引操作,否则会报错)

    2023年04月09日
    浏览(43)
  • Spring boot 实现 Elasticsearch 动态创建索引

    查找了很多方法都是通过Spring EL表达式实现 @Document(IndexName=\\\" #{demo.getIndexName} \\\") 这种方式的问题在于没法解决数据库里生成的序号,例如我希望通过公司ID生成索引编号。后来在外网上找到一个大佬提出的解决方案,这位大佬把两种方案都实现了一遍。 通过entityId自定义index

    2024年02月11日
    浏览(28)
  • 使用ElasticsearchRepository和ElasticsearchRestTemplate操作Elasticsearch,Spring Boot整合Elasticsearch

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 Elasticsearch官网参考文档:https://www.elastic.co/guide/index.html Elasticsearch官方下载地址:https://www.elastic.co/cn/downloads/elasticsearch https://docs.spring.io/spring-data/elasticsearch/reference/ 添加依赖 修改yml配置文件 【自定义

    2024年04月22日
    浏览(41)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包