1.安装好elasticsearch6.5.4
2.引入pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3.创建实体
@Document(indexName = "product", type = "book")
public class Book implements Serializable {
@Id
String id;
String name;
String message;
String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
4.编写dao
注意@Repository很必要
@Repository
public interface BookDao extends ElasticsearchRepository<Book, String> {
}
5.编写BookController
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookDao bookDao;
/**
* 1、查 id
* @param id
* @return
*/
@GetMapping("/get/{id}")
public Book getBookById(@PathVariable String id) {
return bookDao.findById(id).get();
}
/**
* 2、查 ++:全文检索(根据整个实体的所有属性,可能结果为0个)
* @param q
* @return
*/
@GetMapping("/select/{q}")
public List<Book> testSearch(@PathVariable String q) {
QueryStringQueryBuilder builder = new QueryStringQueryBuilder(q);
Iterable<Book> searchResult = bookDao.search(builder);
Iterator<Book> iterator = searchResult.iterator();
List<Book> list = new ArrayList<Book>();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
/**
* 4、增
* @param book
* @return
*/
@PostMapping("/insert")
public Book insertBook(Book book) {
bookDao.save(book);
return book;
}
/**
* 5、删 id
* @param id
* @return
*/
@DeleteMapping("/delete/{id}")
public Book insertBook(@PathVariable String id) {
Book book = bookDao.findById(id).get();
bookDao.delete(book);
return book;
}
/**
* 6、改
* @param book
* @return
*/
@PutMapping("/update")
public Book updateBook(Book book) {
bookDao.save(book);
return book;
}
}
6.编写application.yml文件
server:
port: 8080
spring:
data:
elasticsearch:
cluster-nodes: localhost:9300
repositories:
enabled: true
local: false
name: elasticsearch
测试:
新增
删除
查询详情