导入pom.xml依赖
<!--SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>-->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>
application.properties配置
spring.elasticsearch.jest.uris=http://192.168.2.129:9200
Test
package com.hnjd.elastic;
import com.hnjd.elastic.bean.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot03ElasticApplicationTests {
@Autowired
JestClient jestClient;
@Test
public void contextLoads() {
//1.给Es中索引(保存)一个文档
Article article = new Article();
article.setId(1);
article.setTitle("好消息");
article.setAuthor("zhangsan");
article.setContent("Hello World");
//构建一个索引功能
Index index = new Index.Builder(article).index("hnjd").type("article").build();
try {
//执行
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
//测试搜索
@Test
public void search(){
//查询表达式
String json = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";
//构建搜索功能
Search search = new Search.Builder(json).addIndex("hnjd").addType("article").build();
//执行
try {
SearchResult result = jestClient.execute(search);
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载:https://blog.csdn.net/qq_42811864/article/details/101926238
查看评论