SpringBoot整合Elasticsearch详细步骤以及代码示例(附源码) (2)

application.yml文件配置如下:

server: port: 8080 servlet: context-path: /search spring: application: name: search data: elasticsearch: cluster-name: my-cluster cluster-nodes: localhost:9300 jackson: default-property-inclusion: non_null logging: file: application.log path: . level: root: info com.lifengdi.store.client: DEBUG index-entity: configs: - docCode: store indexName: store type: base documentPath: com.lifengdi.document.StoreDocument

spring.data.elasticsearch.cluster-name:集群名称

spring.data.elasticsearch.cluster-nodes:集群节点地址列表,多个节点用英文逗号(,)分隔

创建ES文档和映射

首先创建一个JAVA对象,然后通过注解来声明字段的映射属性。
spring提供的注解有@Document、@Id、@Field,其中@Document作用在类,@Id、@Field作用在成员变量,@Id标记一个字段作为id主键。

package com.lifengdi.document; import com.lifengdi.document.store.*; import com.lifengdi.search.annotation.DefinitionQuery; import com.lifengdi.search.enums.QueryTypeEnum; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; /** * 门店Document * * @author 李锋镝 * @date Create at 19:31 2019/8/22 */ @Document(indexName = "store", type = "base") @Data @DefinitionQuery(key = "page", type = QueryTypeEnum.IGNORE) @DefinitionQuery(key = "size", type = QueryTypeEnum.IGNORE) @DefinitionQuery(key = "q", type = QueryTypeEnum.FULLTEXT) public class StoreDocument { @Id @DefinitionQuery(type = QueryTypeEnum.IN) @DefinitionQuery(key = "id", type = QueryTypeEnum.IN) @Field(type = FieldType.Keyword) private String id; /** * 基础信息 */ @Field(type = FieldType.Object) private StoreBaseInfo baseInfo; /** * 标签 */ @Field(type = FieldType.Nested) @DefinitionQuery(key = "tagCode", mapped = "tags.key", type = QueryTypeEnum.IN) @DefinitionQuery(key = "tagValue", mapped = "tags.value", type = QueryTypeEnum.AND) @DefinitionQuery(key = "_tagValue", mapped = "tags.value", type = QueryTypeEnum.IN) private List<StoreTags> tags; } 创建索引

ElasticsearchTemplate提供了四个createIndex()方法来创建索引,可以根据类的信息自动生成,也可以手动指定indexName和Settings

@Override public <T> boolean createIndex(Class<T> clazz) { return createIndexIfNotCreated(clazz); } @Override public boolean createIndex(String indexName) { Assert.notNull(indexName, "No index defined for Query"); return client.admin().indices().create(Requests.createIndexRequest(indexName)).actionGet().isAcknowledged(); } @Override public boolean createIndex(String indexName, Object settings) { CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName); if (settings instanceof String) { createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); } else if (settings instanceof Map) { createIndexRequestBuilder.setSettings((Map) settings); } else if (settings instanceof XContentBuilder) { createIndexRequestBuilder.setSettings((XContentBuilder) settings); } return createIndexRequestBuilder.execute().actionGet().isAcknowledged(); } @Override public <T> boolean createIndex(Class<T> clazz, Object settings) { return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings); } 创建映射

ElasticsearchTemplate提供了三个putMapping()方法来创建映射

@Override public <T> boolean putMapping(Class<T> clazz) { if (clazz.isAnnotationPresent(Mapping.class)) { String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath(); if (!StringUtils.isEmpty(mappingPath)) { String mappings = readFileFromClasspath(mappingPath); if (!StringUtils.isEmpty(mappings)) { return putMapping(clazz, mappings); } } else { LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); } } ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz); XContentBuilder xContentBuilder = null; try { ElasticsearchPersistentProperty property = persistentEntity.getRequiredIdProperty(); xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), property.getFieldName(), persistentEntity.getParentType()); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } return putMapping(clazz, xContentBuilder); } @Override public <T> boolean putMapping(Class<T> clazz, Object mapping) { return putMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType(), mapping); } @Override public boolean putMapping(String indexName, String type, Object mapping) { Assert.notNull(indexName, "No index defined for putMapping()"); Assert.notNull(type, "No type defined for putMapping()"); PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(indexName).setType(type); if (mapping instanceof String) { requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON); } else if (mapping instanceof Map) { requestBuilder.setSource((Map) mapping); } else if (mapping instanceof XContentBuilder) { requestBuilder.setSource((XContentBuilder) mapping); } return requestBuilder.execute().actionGet().isAcknowledged(); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgjdp.html