记录的是es5.6.0的Java Api,springboot1.5.6java
@Resource TransportClient transportClient;
/** * 检查索引是否存在 * @param indexName 索引名称 * @return */ public boolean checkIndexExist( String indexName){ IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(indexName); IndicesExistsResponse inExistsResponse = transportClient.admin().indices() .exists(inExistsRequest).actionGet(); return inExistsResponse.isExists(); }
例如在建立索引名为:book以前须要判断book这个索引是否存在。spring
/** * 检查类型是否存在 * 注意: 这种状况默认时 索引已经存在 * @param indexName 索引名 * @param typeName 类型名 * @return */ public boolean checkTypeExist(String indexName,String typeName){ if (!checkIndexExist(indexName)){ return false; } TypesExistsRequest inExistsRequest = new TypesExistsRequest(new String[]{indexName},typeName); TypesExistsResponse inExistsResponse = transportClient.admin().indices().typesExists(inExistsRequest) .actionGet(); return inExistsResponse.isExists(); }
/** * 删除索引 * @param indexName */ public void deleteIndex(String indexName){ if (!checkIndexExist(indexName)) { System.out.println(indexName + " not exists"); } else { DeleteIndexResponse dResponse = transportClient.admin().indices().prepareDelete(indexName) .execute().actionGet(); if (dResponse.isAcknowledged()) { System.out.println("delete index "+indexName+" successfully!"); }else{ System.out.println("Fail to delete index "+indexName); } } }
当一个索引被删除,那么索引下的全部类型和下面的文档将都被删除。json
示例:建立一个索引名books类型名novels的文档。springboot
//构建文档内容 XContentBuilder content = null; try { content = XContentFactory.jsonBuilder().startObject() .field("name", "三体-黑暗森林") .field("author","大刘") .field("date","2017-01-25 14:12:52") .field("id", 1); .field("price",102) content.endObject(); //构建索引 IndexResponse result = transportClient.prepareIndex("books", "novels") .setSource(content) .get(); } catch (IOException e) { e.printStackTrace(); }
/** * 启用高亮字段 * @param builder * @param fields 须要高亮显示的文档字段 */ public void enableHighlight(SearchRequestBuilder builder, String ... fields) { //设置自定义高亮显示 HighlightBuilder highlightBuilder = new HighlightBuilder(); Objects.requireNonNull(fields); for (String field : fields) { highlightBuilder.field(field); } highlightBuilder.preTags("<font color=\"red\">"); highlightBuilder.postTags("</font>"); builder.highlighter(highlightBuilder); } /** * 封装高亮字段搜索结果 * @param hit * @param fields 须要高亮显示的文档字段 */ public void setHighlightResult(SearchHit hit, String ... fields){ Objects.requireNonNull(fields); Map<String, HighlightField> highlightFields = hit.getHighlightFields(); if (Objects.nonNull(highlightFields)){ for (String field : fields) { HighlightField highlight = highlightFields.get(field); if (Objects.nonNull(highlight)){ Text[] fragments = highlight.fragments(); StringBuilder hitStr= new StringBuilder(); for (Text fragment : fragments) { hitStr.append(fragment); } hit.getSource().put(field, hitStr.toString()); } } } }
使用:app
持续更新……post