es--2ElasticSearch结合springboot使用

https://www.bilibili.com/video/BV1py4y1r7Ar?from=search&seid=14817215112859046317
笔记 https://blog.csdn.net/qq_20051535/category_10772271.html

一、配置

1、引入依赖
2、建立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;
		}
	}

三、复杂查询

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值