SpringBoot接入ElasticSearch7.10.2详细教程

一、搭建项目

目前时间 2021年1月27日 我们将使用当前最新版本ElasticSearch,即7.10.2版本配合SpringBoot搭建,由于新版本只有ElasticSearch官方提供了开发工具,所以我们采用官方工具。

我们因为不采用Spring为我们提供的接入方式,下一步填好信息后选择不需要选NoSQL里面任何选项,选一个Web直接一路Next等待完成

 

二、导入Maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qiruipeng</groupId>
    <artifactId>es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>es</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.2</version>
            </plugin>
        </plugins>
    </build>

</project>

 

三、建立Config

建立一个类,我们命名为 ElasticSearchConfig 把它放在了Config文件夹作为我们的配置文件

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ruipeng.qi
 **/
@Configuration
public class ElasticSearchConfig {

	public  static final RequestOptions COMMON_OPTIONS;
	static {
		RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
		COMMON_OPTIONS = builder.build();
	}

	@Bean
	public RestHighLevelClient client() {
		return new RestHighLevelClient(
				RestClient.builder(
						new HttpHost("127.0.0.1", 9200)));
	}
}

 

四、Test测试新增

我们尝试新增一个User对象。我们采用内部类形式定义对象,之后新建一个实例,让他的名字叫 zhangsan;性别是 男;年龄18

注意,下面代码中 @Data 注解作用是自动添加 GET 和 SET 方法,和项目本身没有太大关系

运行后尝试查询是否添加成功。

import com.alibaba.fastjson.JSON;
import com.qiruipeng.es.config.ElasticSearchConfig;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
class EsApplicationTests {

	@Autowired
	private RestHighLevelClient client;

	/**
	 * 测试存储数据到es
	 * 更新也可以
	 */
	@Test
	void indexData() throws IOException {
		IndexRequest indexRequest = new IndexRequest("users");
		indexRequest.id("1");
		User user = new User("zhangsan", "男", 18);
		String jsonString = JSON.toJSONString(user);
		indexRequest.source(jsonString, XContentType.JSON);

		//执行操作
		IndexResponse index = client.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);

		//提取有用的操作数据
		System.out.println(index);
	}

	@Data
	static class User{
		private String userName;
		private String gender;
		private Integer age;

		public User(String userName, String gender, Integer age) {
			this.userName = userName;
			this.gender = gender;
			this.age = age;
		}
	}

}

 

五、检测是否成功

我们通过Kinaba查询是否添加成功:

GET users/_search

返回结果如下,可见添加已经成功

{
  "took" : 50,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "users",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "age" : 18,
          "gender" : "男",
          "userName" : "zhangsan"
        }
      }
    ]
  }
}

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
在Spring Boot中连接Elasticsearch,你需要完成以下几个步骤: 1. 添加Elasticsearch依赖:在你的项目的pom.xml文件中,添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置Elasticsearch连接信息:在你的`application.properties`或者`application.yml`文件中,添加以下配置信息: ```properties spring.data.elasticsearch.cluster-name=your-cluster-name spring.data.elasticsearch.cluster-nodes=localhost:9300 ``` 3. 创建实体类:创建一个Java类来映射Elasticsearch中的文档。例如,如果你要存储一些产品信息,可以创建一个`Product`类,并使用注解来标记字段和文档的相关信息。 ```java @Document(indexName = "products", type = "_doc") public class Product { @Id private String id; private String name; private String description; // 省略构造函数、getter和setter方法 } ``` 4. 创建Elasticsearch仓库接口:创建一个继承自`ElasticsearchRepository`的接口,用于对Elasticsearch进行CRUD操作。例如,对于`Product`实体类,可以创建一个`ProductRepository`接口。 ```java public interface ProductRepository extends ElasticsearchRepository<Product, String> { // 可以自定义查询方法 } ``` 5. 使用Elasticsearch操作数据:在你的服务类或控制器中,注入`ProductRepository`,并使用它来进行数据操作。例如: ```java @Autowired private ProductRepository productRepository; // 保存一个产品 Product product = new Product("1", "手机", "这是一个手机"); productRepository.save(product); // 根据ID查询一个产品 Optional<Product> optionalProduct = productRepository.findById("1"); ``` 以上是连接Elasticsearch的基本步骤,你可以根据自己的需求进一步扩展和定制。希望能对你有所帮助!如果有任何问题,请随时提问。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员麻薯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值