1、创建项目
SpringBoot 默认支持两种技术来和ES交互;
1、Jest(默认不生效:需要导入jest相关包)
2、SpringData ElasticSearch
2、测试Jest与ES交互
2.1注释掉
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
2.2 导入
<dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>6.3.1</version> </dependency>
2.3 配置
spring.elasticsearch.jest.uris=http://localhost:9200
2.4 User
public class User{ @JestId private Integer id; private String name; }
2.5 测试
@Autowired JestClient jestClient; @Test //插入数据 public void test1() throws IOException { User user = new User(); user.setId(2); user.setName("user2"); //index,type不能有大写英文字母 Index index = new Index.Builder(user).index("jest_index").type("jest_type").build(); jestClient.execute(index); } @Test //索引数据 public void test2() throws IOException { String query = "{ " + " "query" : { " + " "match" : { " + " "name" : "user2" " + " } " + " } " + "}"; Search build = new Search.Builder(query).addIndex("jest_index").addType("jest_type").build(); SearchResult execute = jestClient.execute(build); System.out.println(execute); }
3、SpringBoot 整合SpringData ElasticSearch
一定要选择合适的ElasticSearch否则可能会出现意想不到的错误:https://github.com/spring-projects/spring-data-elasticsearch
3.1 添加之前注释掉的依赖,jest可以注释掉了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
3.2 application.properties
spring.data.elasticsearch.cluster-name=elasticsearch spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
3.3. User
@Document(indexName = "index2",type = "type2") public class User{ private Integer id; private String name; }
3.4 repository(dao)
//User:操作的对象,Integer:主键的类型 public interface UserRepository extends ElasticsearchRepository<User,Integer> { }
3.5 测试
@Autowired private UserRepository repository; @Test public void test(){ User user = new User(); user.setId(5); user.setName("user5"); repository.index(user); } @Test public void test2(){ //或者浏览器访问:http://localhost:9200/index2/type2/5 Optional<User> byId = repository.findById(5); System.out.println(byId.get()); }
3.6 补充:自定义查询
public interface UserRepository extends ElasticsearchRepository<User,Integer> { //可以自定义实现名字的定义必须按照官方文档:https://docs.spring.io/spring-data/elasticsearch/docs/3.1.10.RELEASE/reference/html/ public User findByName(String username); }
3.7 使用 ElasticsearchTemplate(略)