es 插入数据_ES + Spring boot的正确姿势

前言

在前边我们探讨了ES的基本概念以及根据不同的场景选择数据迁移的方案。在这一篇我们来探讨如何与Spring boot集成,以及为了平滑地从Mysql迁移到ES中我们如何”翻译SQL“。

一、Spring Boot集成ES

第一步我们就要实现Spring boot和ES集成,在Spring boot中主要有Java REST Clientspring-data-elasticsearch两种方式,这里我建议使用Elasticsearch官方提供的Java High Level REST Client来集成,也方便在生产环境中使用阿里云的ES云服务。关键的版本信息如下:

  • ES集群:7.3.0

  • ES相关依赖:7.3.0

这里有两点需要注意:

  • High Level Client能够向上兼容,例如7.3.0版本的Java High Level REST Client能确保与大于等于7.3.0版本的Elasticsearch集群通信。为了保证最大程度地使用最新版客户端的特性,推荐High Level Client版本与集群版本一致。

  • 在集成的过程中可能会踩到一些坑,因为Spring Boot的版本、ES集群的版本、High Level Client的版本之间会存在”关联关系“,所以当Demo无法正常跑起来的时候能做的就是多尝试一些High Level Client版本。

1、pom依赖
org.elasticsearch.clientelasticsearch-rest-high-level-client7.3.0

org.elasticsearchelasticsearch7.3.0

org.elasticsearch.clientelasticsearch-rest-client7.3.0

org.elasticsearch.pluginrank-eval-client7.3.0

org.elasticsearch.pluginlang-mustache-client7.3.0
复制代码

2、初始化客户端

@Configuration
public class EsConfig {

@Value("${elasticsearch.host}")
public String host;

/**
* 之前使用transport的接口的时候是9300端口,现在使用HighLevelClient则是9200端口
*/
@Value("${elasticsearch.port:9200}")
public int port;

public static final String SCHEME = "http";

@Value("${elasticsearch.username:admin}")
public String username;

@Value("${elasticsearch.authenticationPassword}")
public String authenticationPassword;

@Bean(name = "remoteHighLevelClient")
public RestHighLevelClient restHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username,
authenticationPassword));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, SCHEME)).
setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider));
return new RestHighLevelClient(builder);
}
}
复制代码

在上边的代码中需要注意username和authenticationPassword的认证信息都是在Kibana中设置的。

二、Java API

下面的代码片段均能在单元测试中正常运行,在执行下边的单元测试之前,我们先创建一个_template,大家可以选择在Kibana提供的Dev Tools里边执行。

PUT _template/hero_template
{
"index_patterns&
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现搜索引擎一般需要以下步骤: 1. 数据库建表和数据导入:根据需要建立相应的数据库表,并导入数据。 2. Elasticsearch安装和配置:安装Elasticsearch,配置Elasticsearch集群,并将数据导入到Elasticsearch中。 3. Spring Boot和Vue.js项目搭建:使用Spring Boot和Vue.js框架搭建项目。 4. 搜索功能实现:使用Elasticsearch进行搜索功能的实现。 具体实现步骤如下: 1. 数据库建表和数据导入 根据需求建立相应的数据库表,并将数据导入到数据库中。这里以MySQL为例,建立一个books表: CREATE TABLE `books` ( `id` int NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `author` varchar(255) DEFAULT NULL, `content` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 将数据导入到books表中: INSERT INTO `books` (`id`, `title`, `author`, `content`) VALUES (1, 'Java编程思想', 'Bruce Eckel', 'Java编程思想是一本Java入门书籍。'), (2, 'Spring Boot实战', 'Craig Walls', 'Spring Boot实战是一本介绍Spring Boot框架的书籍。'), (3, 'Vue.js实战', '梁灏', 'Vue.js实战是一本介绍Vue.js框架的书籍。'); 2. Elasticsearch安装和配置 安装Elasticsearch,配置Elasticsearch集群,并将数据导入到Elasticsearch中。这里以Elasticsearch 7.2.0为例,安装步骤如下: (1)下载Elasticsearch 官网下载地址:https://www.elastic.co/downloads/elasticsearch (2)解压并启动Elasticsearch 解压后进入bin目录,执行以下命令启动Elasticsearch: ./elasticsearch (3)安装中文分词器 Elasticsearch默认使用英文分词器,需要安装中文分词器,这里使用IK Analyzer中文分词器。IK Analyzer的GitHub地址为:https://github.com/medcl/elasticsearch-analysis-ik 下载IK Analyzer件: wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.2.0/elasticsearch-analysis-ik-7.2.0.zip 将件安装到Elasticsearch中: ./elasticsearch-plugin install file:///path/to/elasticsearch-analysis-ik-7.2.0.zip (4)将数据导入到Elasticsearch中 使用Elasticsearch的API将数据库中的数据导入到Elasticsearch中。 3. Spring Boot和Vue.js项目搭建 使用Spring Boot和Vue.js框架搭建项目,这里不再赘述。 4. 搜索功能实现 (1)在Spring Boot中使用Elasticsearch进行搜索 使用Spring Data Elasticsearch实现与Elasticsearch的交互,具体步骤如下: 1. 在pom.xml中添加Spring Data Elasticsearch依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> 2. 在application.yml中配置Elasticsearchspring: data: elasticsearch: cluster-name: elasticsearch cluster-nodes: 127.0.0.1:9300 3. 创建一个Book实体类,并使用@Document注解标注该实体类对应的Elasticsearch索引和类型: @Document(indexName = "books", type = "book") public class Book { @Id private Long id; private String title; private String author; private String content; // getter和setter方法省略 } 4. 创建一个BookRepository接口,继承ElasticsearchRepository接口: public interface BookRepository extends ElasticsearchRepository<Book, Long> { } 5. 在BookService中实现搜索功能: @Service public class BookService { @Autowired private BookRepository bookRepository; public List<Book> search(String keyword) { QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "title", "author", "content"); Iterable<Book> iterable = bookRepository.search(queryBuilder); List<Book> books = new ArrayList<>(); iterable.forEach(books::add); return books; } } (2)在Vue.js中调用搜索接口 使用axios库调用Spring Boot的接口,具体步骤如下: 1. 安装axios库: npm install axios --save 2. 在Vue.js中调用搜索接口: <script> import axios from 'axios'; export default { data() { return { keyword: '', books: [] } }, methods: { search() { axios.get('/api/search?keyword=' + this.keyword).then(response => { this.books = response.data; }).catch(error => { console.log(error); }); } } } </script> 以上就是使用Spring Boot和Vue.js实现Elasticsearch搜索引擎的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值