我们在 springBoot集成elasticsearch 中完成了集成,但是我们需要知道如何使用。其实es和mysql很相识。
es->索引->字段
mysql->表->字段
所以索引和表是一个层级的。
接下来,该说下如何使用。
一:查询索引
public boolean queryIndex(String myIndex) { try { GetIndexRequest request = new GetIndexRequest(myIndex); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); return exists; } catch (Exception e) { return false; } }二:创建索引
public Result addIndex(String myIndex) { try { //查询索引是否存在 boolean exists =this.queryIndex(myIndex); if (exists) { return Result.sendSuccess("索引:" + myIndex + "已经存在"); } //创建索引 CreateIndexRequest indexRequest = new CreateIndexRequest(myIndex); CreateIndexResponse response = client.indices() .create(indexRequest, RequestOptions.DEFAULT); boolean flag = response.isAcknowledged(); if (flag) { return Result.sendSuccess("索引:" + myIndex + "创建索引成功!"); } else { return Result.sendSuccess("索引:" + myIndex + "创建索引失败!"); } } catch (Exception e) { e.printStackTrace(); return Result.sendFailure("新增异常"); } }三:添加文档(相当于向数据库添加数据)
public Result addDoc(String myIndex, String id, Object user) { try { IndexRequest request = new IndexRequest(myIndex); String source = JSONObject.toJSonString(user); // 手动设置id request.id(id); request.source(source, XContentType.JSON); IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println(response.getResult()); return Result.sendSuccess("索引:" + myIndex + "数据成功!", response.getResult()); } catch (Exception e) { e.printStackTrace(); return Result.sendFailure("添加数据失败"); } }四:修改文档
其实和三一样,id一定要有。因为es会检查es中是否存在id已经存在,如果id存在。则更新,如果id不存在,则新增。
五:删除文档public Result deleteDoc(String myIndex, String id) { try { DeleteRequest deleteRequest = new DeleteRequest(myIndex, id); DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT); return Result.sendSuccess("删除文档成功", response.getResult()); } catch (Exception e) { e.printStackTrace(); return Result.sendFailure("删除成功!"); } }六:查询文档
其实查询才是最麻烦的地方,因为这个查询比较多。我们这介绍下分页和查询。查询条件的EsUserDto
@ApiModelProperty(value = "查询条件") private String name; @ApiModelProperty(value = "索引") private String myIndex; @ApiModelProperty(value = "当前页") private Integer pageNum; @ApiModelProperty(value = "当前页大小") private Integer pageSize;
查询组装
public Result queryDoc(EsUserDto esUser) { try { //查询条件设置 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //设置分页相关 sourceBuilder.from((esUser.getPageNum() - 1) * esUser.getPageSize()); //每页查询数据 sourceBuilder.size(esUser.getPageSize()); //设置条件查询 BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery(); if (esUser.getName() != null) { boolBuilder.must(QueryBuilders.matchQuery("name", esUser.getName())); } boolBuilder.should(); sourceBuilder.query(boolBuilder); //按时间排序 降序 sourceBuilder.sort("createTime", SortOrder.DESC); //设置索引 SearchRequest searchRequest = new SearchRequest(esUser.getMyIndex()); searchRequest.source(sourceBuilder); System.out.println("搜索语句是:" + sourceBuilder.toString()); SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT); System.out.println("查询条件:" + search); SearchHits hits = search.getHits(); SearchHit[] hitsArr = hits.getHits(); TotalHits totalHits = hits.getTotalHits(); long total = totalHits.value; ListuserList = new ArrayList<>(); for (SearchHit documentFields : hitsArr) { EsUser esUsers = JSONObject.toJavaObject(JSON.parseObject(documentFields.getSourceAsString()), EsUser.class); userList.add(esUsers); } Map map = new HashMap<>(8); map.put("total", total); map.put("data", userList); return Result.sendSuccess("查询成功", map); } catch (Exception e) { e.printStackTrace(); return Result.sendFailure("查询异常!"); } }
上面则查询成功了。
七:实现高亮public Result searchHigh(EsUserDto esUserDto){ SearchRequest searchRequest = new SearchRequest(esUserDto.getMyIndex()); //search builder SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("name", esUserDto.getName())); sourceBuilder.from((esUserDto.getPageNum() - 1) * esUserDto.getPageSize()); sourceBuilder.size(esUserDto.getPageSize()); sourceBuilder.timeout(new Timevalue(60, TimeUnit.SECONDS)); //sort sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC)); //highlight HighlightBuilder highlightBuilder = new HighlightBuilder(); HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("name"); highlightTitle.preTags(""); highlightTitle.postTags(""); highlightBuilder.field(highlightTitle); sourceBuilder.highlighter(highlightBuilder); // add builder into request searchRequest.indices(esUserDto.getMyIndex()); searchRequest.source(sourceBuilder); //response SearchResponse searchResponse = null; try { searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } Timevalue took = searchResponse.getTook(); //search hits SearchHits hits = searchResponse.getHits(); long totalHits = hits.getTotalHits().value; SearchHit[] searchHits = hits.getHits(); ListpostList = new ArrayList<>(); for (SearchHit hit : searchHits) { String str = hit.getSourceAsString(); EsUser esPost = JSONObject.parseObject(str, EsUser.class); Map highlightFields = hit.getHighlightFields(); HighlightField highlight = highlightFields.get("name"); if (highlight != null) { Text[] fragments = highlight.fragments(); String fragmentString = fragments[0].string(); esPost.setName(fragmentString); } postList.add(esPost); } return Result.sendSuccess("查询成功",postList); } }