导包
导包可以根据 文档 里导入依赖
这里就不写依赖了
关键字搜索
import com.google.gson.Gson;
import com.leyou.pojo.Item;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsdemoFindMatch {
private RestHighLevelClient client;
private Gson gson = new Gson();
/**
* 先执行
*/
@Before
public void init (){
// 初始化HighLevel客户端
client = new RestHighLevelClient(
RestClient.builder(
HttpHost.create("http://127.0.0.1:9201"),
HttpHost.create("http://127.0.0.1:9202"),
HttpHost.create("http://127.0.0.1:9203")
)
);
}
/**
* 关键字搜索match
*/
@Test
public void findMatch() throws IOException {
//创建搜索对象
SearchRequest searchRequest = new SearchRequest();
//构造查询工具
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 添加查询条件,通过QueryBuilders获取各种查询
searchSourceBuilder.query(QueryBuilders.matchQuery("字段名","内容"));
searchRequest.source(searchSourceBuilder);
//搜索
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
//解析
SearchHits hits = response.getHits();
SearchHit[] hitsHits = hits.getHits();
for (SearchHit hitsHit : hitsHits) {
//获得数据
String source = hitsHit.getSourceAsString();
//反序列化
Item item = gson.fromJson(source, Item.class);
//打印
System.out.println("item"+item);
}
}
/**
* 后执行
*/
@After
public void close(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果打印
itemItem(id=2, title=坚果手机R1, category=手机, brand=锤子, price=3699.0, images=http://image.csdn.com/13123.jpg)
itemItem(id=1, title=小米手机7, category=手机, brand=小米, price=3299.0, images=http://image.csdn.com/13123.jpg)