今日上市的50亿项目ElasticSearch了解一下2
在springboot项目中操作ElasticSearch
1.pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
版本和parent版本相关,注意安装的es要和springboot对应(springboot 1.5.17对应es 2.4)
2.application.yml配置
spring:
data:
elasticsearch:
#默认为elasticsearch,是es安装配置文件中的cluster-name
cluster-name: my-application
#配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode,注意端口和配置文件中不一样http是9200,java中默认用9300
cluster-nodes: 118.24.78.36:9300
注意 是在spring下面
3.代码操作es 方式一
包名没在代码中,自己定包路径
用实体对应es中的index,type,id
entity
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
//指定的 index 和type
@Document(indexName = "product", type = "book")
public class Book {
//指定的id
@Id
String id;
String name;
String message;
String type;
}
//getter setter 省略
dao 直接继承ElasticsearchRepository,使用其中默认的api
import com.baseweb.myfield.esDemo.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BookDao extends ElasticsearchRepository<Book,String> {
}
controller 省略service层,bookDao都是操作ElasticsearchRepository中的接口
import com.baseweb.myfield.esDemo.dao.BookDao;
import com.baseweb.myfield.esDemo.entity.Book;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookDao bookDao;
/**
* 1、新增
* @param book
* @return
*/
@PostMapping("/insert")
public Book insertBook(@RequestBody Book book) throws Exception {
if(book == null){
throw new Exception("boot 为空");
}
bookDao.save(book);
return book;
}
/**
* 2、查 通过id
* @param id
* @return
*/
@GetMapping("/get/{id}")
public Book getBookById(@PathVariable String id) {
return bookDao.findOne(id);
}
/**
* 3、查 通过其他属性++:全文检索(根据整个实体的所有属性,可能结果为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、更新数据,通过id
* @param book
* @return
*/
@PutMapping("/update")
public Book updateBook(@RequestBody Book book) {
bookDao.save(book);
return book;
}
/**
* 5、删 通过id
* @param id
* @return
*/
@DeleteMapping("/delete/{id}")
public Book insertBook(@PathVariable String id) {
Book book = bookDao.findOne(id);
bookDao.delete(id);
return book;
}
}
4.测试
启动springboot项目
用postman发送接口测试
开始查询一下es,数据为空
新增
查询es所有数据,有了
测试查询接口,有数据
测试更新接口,注意要用id去更新,所以id是不能变的
再次查询
说明更新成功
通过属性查询
删除
再次查询
返回为空,删除成功