昨天把拼了一半的注解+Elasticsearch积木放下了,因为东西太多了拼不好,还容易乱。休息了一晚上接着来。
接着昨天,创建elasticsearch文档注解(相当于数据表的注解):
/** * elastic文档注解,定义每个elasticsearch文档上的属性 * * @author xiangwang */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface Document { String index(); String type() default "_doc"; boolean useServerConfiguration() default false; short shards() default 1; short replicas() default 0; String refreshInterval() default "1s"; String indexStoreType() default "fs"; }
然后再创建elasticsearch文档(相当于数据表):
/** * elastic文档对象 * * @author xiangwang */ @Document(index = "document", type = "_doc", shards = 1, replicas = 0) public class ElasticDocument { private static final long serialVersionUID = 2879048112350101009L; // 文档编码 @DocField(name = "guid", type = FieldType.Keyword) protected String guid = ""; // 标题 @DocField(name = "title", type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word") protected String title = ""; // 文档创建时间(资源实际创建时间) @DocField(name = "createtime", type = FieldType.Long) protected long createtime; // 文档更新时间(资源实际更新时间) @DocField(name = "updatetime", type = FieldType.Long) protected long updatetime; public ElasticDocument() { } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getCreatetime() { return createtime; } public void setCreatetime(long createtime) { this.createtime = createtime; } public long getUpdatetime() { return updatetime; } public void setUpdatetime(long updatetime) { this.updatetime = updatetime; } @Override public String toString() { return String.format("{\"guid\":\"%s\", \"title\":\"%s\", \"createtime\":%d, " + "\"updatetime\":%d}", guid, title, createtime, updatetime); } }
这里面的@Document就是刚才创建的文档注解。
最后,创建一个真正的执行者,就由它来完成所有材料的拼装:
/** * ElasticDao * * @author xiangwang */ @Component public class ElasticDao { // ElasticConfiguration中定义的Bean对象 @Autowired private RestHighLevelClient client; /** * 索引是否存在 * */ public boolean indexExist(final String index) { try { return client.indices().exists(new GetIndexRequest(index), RequestOptions.DEFAULT); } catch (IOException e) { System.out.println("index exist exception"); } return false; } /** * 解析类注解,获取包括父类字段在内的所有字段 * 因为解析的时候,会把父类及自身的一些额外字段给解析进去 * 如logger、serialVersionUID等 * 所以需要把这些无用的字段排除掉 * 这里不存在继承,所以直接调用clazz.getDeclaredFields() * 另外,如果存在继承关系,该怎么处理呢?(可以思考一下) * */ public static List<Field> getAllDeclaredFields(Class<?> clazz) { return new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())); } /** * 创建索引,前面都是为了实现它作准备 * 这里会通过注解,一路解析文档的字段,拼接成可执行的脚本交给elasticsearch的api去执行 * */ public boolean createIndex(final String index, final Class<?> clazz) { try { Document document = (Document) clazz.getAnnotation(Document.class); int shards = document.shards(); int replicas = document.replicas(); if (indexExist(index)) { re