默认支持两种技术和es交互
这里有个大的前提,就是springboot的版本不能太高。必须是1.5版本的。因为2.x版本的springboot已经没有这个jest的自动配置了。
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.12.RELEASEversion>
<relativePath/>
parent>
<dependency>
<groupId>io.searchboxgroupId>
<artifactId>jestartifactId>
<version>5.3.4version>
dependency>
在application.properties配置文件中设置
spring.elasticsearch.jest.uris=http://120.78.152.93:9200/
新建一个Article类,其中 @JestId是设置主键的意思。
@Data
public class Article {
@JestId
private Integer id;
private String title;
private String desc;
private String context;
}
@Autowired
JestClient jestClient;
@Test
public void testEs(){
Article article=new Article();
article.setId(1);
article.setDesc("hello es");
article.setContext("第一个es");
//构建一个索引
Index build = new Index.Builder(article).index("jf3q").type("news").build();
try {
//执行
jestClient.execute(build);
}catch (IOException e){
e.printStackTrace();
}
}
![image.png](https://img-blog.csdnimg.cn/img_convert/c2bbda028647ba666ee3ba2c91b93b48.png#clientId=u89df12b6-0cea-4&from=paste&height=116&id=u465c6d55&margin=[object Object]&name=image.png&originHeight=116&originWidth=910&originalType=binary&ratio=1&size=16209&status=done&style=none&taskId=u0b5c387a-eaee-4e75-8a7d-5a796c283f1&width=910)
// 测试搜索
@Test
public void testSearch(){
//查询表达式
String json="{\n" +
" \"query\" : {\n" +
" \"match_phrase\" : {\n" +
" \"desc\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";
//构建搜索功能
Search search = new Search.Builder(json).addIndex("jf3q").addType("news").build();
try {
SearchResult result = jestClient.execute(search);
System.out.println(result.getJsonString());//打印json字符串
}catch (Exception e){
e.printStackTrace();
}
我这里用的springboot版本是的1.5.12,然后我的elasticsearch的版本是2.4.6的。springdata es版本是2.1.11
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.5.12.RELEASEversion>
<relativePath/>
parent>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
在application.properties配置文件中设置
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=120.78.152.93:9300
参考文档:https://github.com/spring-projects/spring-data-elasticsearch
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
//自定义方法
public List<Book> findByBooeNameLike(String bookName);
}
@Document(indexName="jf3q",type = "book")
@Data
public class Book {
private Integer id;
private String booeName;
private String author;
}
@Autowired
BookRepository bookRepository;
@Test
public void test(){
// Book book=new Book();
// book.setAuthor("杰凡IT");
// book.setId(1);
// book.setBooeName("有偿问答");
// bookRepository.index(book);
for (Book book : bookRepository.findByBooeNameLike("问")) {
System.out.println(book);
}
}