1-修改pom.xml
释放出注释
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2-application.properties中配置节点名字和节点信息
spring.data.elasticsearch.cluster-name=docker-cluster
spring.data.elasticsearch.cluster-nodes=192.168.3.18:9300
3-启动主类
elasticserach版本 有可能不合适
spring官网->projects->spring data->Spring Data Elasticsearch
版本适配说明:
4-两种用法
4-1实现ElasticRepository接口
4-1-1 bean包下新建Book类
package com.example.springbootelasticsearch.bean;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "test",type = "book") //elasticsearch注解,索引名,类型
public class Book {
private Integer id;
private String bookName;
private String author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", bookName='" + bookName + '\'' +
", author='" + author + '\'' +
'}';
}
}
4-1-2新建repository包BookRepository接口
ElasticsearchRepository<T, ID> :要存取的数据的类型 主键的类型package com.example.springbootelasticsearch.repository;
import com.example.springbootelasticsearch.bean.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
}
4-1-3测试类中
@SpringBootTest
class SpringbootElasticsearchApplicationTests {
@Autowired
BookRepository bookRepository;
@Test
public void test02(){
Book book = new Book();
book.setId(1);
book.setBookName("西游记");
book.setAuthor("吴承恩");
bookRepository.index(book);
}
报错:
Caused by: java.lang.IllegalArgumentException: Rejecting mapping update to [test] as the final mapping would have more than 1 type: [news, book]
解决方法:放入到两个索引中
修改Book类
@Document(indexName = "es01test",type = "book") //elasticsearch注解,索引名,类型
public class Book {
private Integer id;
private String bookName;
private String author;
4-1-4 BookRepository支持自定义方法
package com.example.springbootelasticsearch.repository;
import com.example.springbootelasticsearch.bean.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
public List<Book> findByBookNameLike(String bookName);
}
4-1-5添加测试类方法
@Test
public void test03(){
for (Book book : bookRepository.findByBookNameLike("游")) {
System.out.println(book);
}
}
标签:springboot,bookName,book,Book,elasticsearch,springdata,public,String
From: https://blog.51cto.com/u_12528551/5900189