1.jest的方式
1.1前提
这里有个大的前提,就是springboot的版本不能太高。必须是1.5版本的。因为2.x版本的springboot已经没有这个jest的自动配置了。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
1.2pom引入依赖
<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.4</version>
</dependency>
1.3设置es请求地址
在application.properties配置文件中设置
spring.elasticsearch.jest.uris=http://120.78.152.93:9200/
1.4测试
1.4.1插入一个对象到es中
新建一个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();
}
}
1.4.2全文搜索
// 测试搜索
@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();
}
2.springdata ElasticSeach的方式
2.1pom引入依赖
我这里用的springboot版本是的1.5.12,然后我的elasticsearch的版本是2.4.6的。springdata es版本是2.1.11
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.2配置es的地址
在application.properties配置文件中设置
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=120.78.152.93:9300
2.3两种方式操作es
参考文档:https://github.com/spring-projects/spring-data-elasticsearch
- elasticsearchTemplate 操作es
- 编写一个ElasticsearchRepository 的子接口来操作ES:
- 先新建一个BookRepository
```java
public interface BookRepository extends ElasticsearchRepository
{ //自定义方法 public List findByBooeNameLike(String bookName); }
- 先新建一个BookRepository
```java
public interface BookRepository extends ElasticsearchRepository
2. 新建Book实体
```java
@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);
}
}