版本声明
本次使用的ES版本为6.2.1,要求JDK至少1.8以上,使用SpringBoot完成ES的CRUD操作;
可视化图形界面工具使用head插件,head的项目地址在https://github.com/mobz/elasticsearch-head 。打开cmd窗口,进入head插件的安装目录,执行命令:npm run start 。启动head插件,输入ES的url连接ES;
创建RestHighLevelClient客户端
@Configuration
public class ElasticsearchConfig {
@Value("${配置文件中配置es地址,端口号}")
private String hostlist;
@Bean
public RestHighLevelClient restHighLevelClient(){
//解析hostlist配置信息
String[] split = hostlist.split(",");
//创建HttpHost数组,其中存放es主机和端口的配置信息
HttpHost[] httpHostArray = new HttpHost[split.length];
for(int i=0;i<split.length;i++){
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
//创建RestHighLevelClient客户端
return new RestHighLevelClient(RestClient.builder(httpHostArray));
}
@Configuration注解:声明此类是一共配置类;
使用@Autowired注入RestHighLevelClient对象:
@Autowired
RestHighLevelClient client;
创建索引库
@Test
public void testCreateIndex() throws IOException {
//创建索引请求对象,并设置索引名称
CreateIndexRequest createIndexRequest = new CreateIndexRequest();
//设置索引参数
createIndexRequest.settings(Settings.builder().put("number_of_shards", 1).put("number_of_relicas", 0));
//设置映射
createIndexRequest.mapping("doc", 设置映射的JSON字符串, XContentType.JSON);
//创建索引操作客户端
IndicesClient indices=client.indices();
//创建响应对象
CreateIndexResponse createIndexResponse = indices.create(createIndexRequest);
//得到响应结果
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println(acknowledged);
}
删除索引库
@Test
public void testDeleteIndex()throws IOException{
//删除索引请求对象
DeleteIndexRequest deleteIndexRequest=new DeleteIndexRequest("xc_course");
//删除索引
DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);
//删除索引响应结果
boolean acknowledged = deleteIndexResponse.isAcknowledged();
System.out.println(acknowledged);
}
添加文档
@Test
public void testAddDoc()throws IOException{
//准备json数据
Map<String,Object> jsonMap=new HashMap<>();
jsonMap.put("name":"张三")//以key,value的形式封装添加的数据......
//索引请求对象
IndexRequest indexRequest=new IndexRequest("xc_course","doc");
//指定索引文档内容
indexRequest.source(jsonMap);
//索引响应对象
IndexResponse indexResponse=client.index(indexRequest);
//获取响应结果
DocWriteResponse.Result result=indexResponse.getResult();
System.out.println(result);
}
查询文档
@Test
public void getDoc()throws IOException{
GetRequest getRequest=new GetRequest("xc_course","doc",id值);
GetResponse getResponse = client.get(getRequest);
boolean exists = getResponse.isExists(); //查询是否成功
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();//获取查询的数据
System.out.println(exists);
System.out.println(sourceAsMap);
}
更新文档
@Test
public void updateDoc()throws IOException{
UpdateRequest updateRequest=new UpdateRequest("xc_course","doc",id值);
Map<String,String> map=new HashMap<>();
map.put("name","李四");
updateRequest.doc(map);
UpdateResponse update = client.update(updateRequest);
RestStatus status = update.status();
System.out.println(status);
}
根据id删除文档
@Test
public void testDelDoc()throws IOException{
//参数传入索引名称,类型,id
DeleteRequest deleteRequest1=new DeleteRequest("xc_course","doc","4");
//响应对象
DeleteResponse deleteResponse = client.delete(deleteRequest1);
//获取响应结果
DocWriteResponse.Result result = deleteResponse.getResult();
System.out.println(result);
}
搜索使用DSL方式完成
DSL(Domain Specific Language)是ES提出的基于json的搜索方式,在搜索时传入特定的json格式的数据来完成不 同的搜索需求
搜索全部数据
@Test
public void testSeachAll() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//matchAllQuery搜索全部
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
//查询结果集以map形式显示
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String name = (String) sourceAsMap.get("name");
String studymodel =(String) sourceAsMap.get("studymodel");
String description=(String) sourceAsMap.get("description");
System.out.println(name+" "+studymodel+" "+description);
}
}
分页查询
@Test
public void testSeachPage() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//查询页码
searchSourceBuilder.from(0);
//每页显示条目数
searchSourceBuilder.size(1);
//搜索方式
//matchAllQuery搜索全部
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
//查询结果集以map形式显示
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String name = (String) sourceAsMap.get("name");
String studymodel =(String) sourceAsMap.get("studymodel");
String description=(String) sourceAsMap.get("description");
System.out.println(name+" "+studymodel+" "+description);
}
}
精确查询
@Test
public void testSeachTermQuery() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//termQuery精确查询
//使用其他字段查询
//searchSourceBuilder.query(QueryBuilders.termQuery("name","java"));
//使用id查询
String[] ids={"1","2"};
searchSourceBuilder.query(QueryBuilders.termsQuery("_id",ids));
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
//查询结果集以map形式显示
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String name = (String) sourceAsMap.get("name");
String studymodel =(String) sourceAsMap.get("studymodel");
String description=(String) sourceAsMap.get("description");
System.out.println(index+" "+type+" "+id+" "+score+" "+sourceAsString);
System.out.println(name+" "+studymodel+" "+description);
}
}
全文检索(搜索关键字进行分词匹配)
@Test
public void testSeachMatchQuery() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//matchQuery全文检索,minimumShouldMatch:分词后最低应该匹配%,才会显示;
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "spring 开发 java").minimumShouldMatch("80%"));
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
全文检索(关键字匹配多个字段,加权)
@Test
public void testSeachMultiMatchQuery() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//multiMatchQuery全文检索,条件匹配多个字段;
// minimumShouldMatch:分词后最低应该匹配%,才会显示
// field:向指定字段增加权重(X*10),优先显示;
searchSourceBuilder.query(QueryBuilders.multiMatchQuery( "spring java","name","description")
.minimumShouldMatch("50%").field("name",10)
);
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
布尔查询:
需求:既要满足name匹配查询,也要满足studymodel精确查询;
@Test
public void testSeachBool() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//精确查询studymodel字段
TermQueryBuilder termQuery = QueryBuilders.termQuery("studymodel", "201002");
//分词查询name字段
MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "开发");
//创建布尔查询对象
BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
boolQueryBuilder.must(termQuery);
boolQueryBuilder.must(matchQuery);
//加入到query中
searchSourceBuilder.query(boolQueryBuilder);
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
//日期格式化对象
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
过滤器查询
需求:查询价格区间
@Test
public void testSeachFilter() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//精确查询studymodel字段
TermQueryBuilder termQuery = QueryBuilders.termQuery("studymodel", "201001");
//创建布尔查询对象
BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
boolQueryBuilder.must(termQuery);
//过滤
boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(70).lte(100));
//加入到query中
searchSourceBuilder.query(boolQueryBuilder);
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description","price"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
排序
@Test
public void testSeachSort() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//精确查询studymodel字段
TermQueryBuilder termQuery = QueryBuilders.termQuery("studymodel", "201001");
//创建布尔查询对象
BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
boolQueryBuilder.must(termQuery);
//过滤
boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(50).lte(100));
//加入到query中
searchSourceBuilder.query(boolQueryBuilder);
//排序
searchSourceBuilder.sort("_id", SortOrder.DESC);
searchSourceBuilder.sort("price", SortOrder.ASC);
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description","price"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//匹配到的总记录数
long totalHits = hits.getTotalHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//结果集名称
String index = hit.getIndex();
//类型
String type = hit.getType();
//主键id
String id = hit.getId();
//匹配的分数(查询全部,所以匹配分数相同)
float score = hit.getScore();
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(id+""+sourceAsString);
}
}
搜索关键字高亮
@Test
public void testSeachHighlight() throws IOException {
//搜索请求对象
SearchRequest searchRequest=new SearchRequest("xc_course");
//指定类型
searchRequest.types("doc");
//搜索源构建对象
SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//搜索方式
//匹配查询name字段
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "基础");
//加入到query中
searchSourceBuilder.query(matchQueryBuilder);
//高亮设置
HighlightBuilder highlightBuilder=new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");//设置前缀
highlightBuilder.postTags("</font>");//设置前缀
//设置高亮字段
highlightBuilder.fields().add(new HighlightBuilder.Field("name")); //为name字段设置高亮
highlightBuilder.fields().add(new HighlightBuilder.Field("description"));//为description字段设置高亮
searchSourceBuilder.highlighter(highlightBuilder);
//source源字段过滤,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括那个字段
searchSourceBuilder.fetchSource(new String[]{"name","studymodel","description","price"},new String[]{});
//向搜索请求对象中设置搜索源
searchRequest.source(searchSourceBuilder);
//执行搜索,向ES发起http请求
SearchResponse searchResponse = client.search(searchRequest);
//搜索结果
SearchHits hits = searchResponse.getHits();
//得到匹配度高的文档
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
//取出高亮字段内容
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (highlightFields!=null){
HighlightField nameField = highlightFields.get("name");
if (nameField!=null){
Text[] fragments = nameField.getFragments();
StringBuffer stringBuffer=new StringBuffer();
for (Text test : fragments) {
stringBuffer.append(test);
}
System.out.println(stringBuffer.toString());
}
}
//查询结果集,以字符串形式显示
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
以上为本人做的总结,希望可以帮到各位,如有问题可加QQ:980542565