java – 如何使用Spring数据与弹性搜索别名进行交互
发布时间:2020-12-15 00:59:39 所属栏目:Java 来源:网络整理
导读:嗨,我正在使用弹性搜索 Spring数据.我的项目的域结构不断变化.所以我必须删除索引才能每次更改映射.为了解决这个问题,我正在使用别名. 我用以下方法创建了一个Alias: elasticsearchTemplate.createIndex(Test.class);elasticsearchTemplate.putMapping(Test
嗨,我正在使用弹性搜索
Spring数据.我的项目的域结构不断变化.所以我必须删除索引才能每次更改映射.为了解决这个问题,我正在使用别名.
我用以下方法创建了一个Alias: elasticsearchTemplate.createIndex(Test.class); elasticsearchTemplate.putMapping(Test.class); String aliasName = "test-alias"; AliasQuery aliasQuery = new AliasBuilder() .withIndexName("test") .withAliasName(aliasName).build(); elasticsearchTemplate.addAlias(aliasQuery); 我有一个测试类: 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.FieldIndex import org.springframework.data.elasticsearch.annotations.FieldType import org.springframework.data.elasticsearch.annotations.Setting @Document(indexName = "test",type = "test") @Setting(settingPath = 'elasticSearchSettings/analyzer.json') class Test extends BaseEntity{ @Id @Field(type = FieldType.String,index = FieldIndex.not_analyzed) String id @Field(type = FieldType.String,index = FieldIndex.analyzed,indexAnalyzer = "generic_analyzer",searchAnalyzer = "generic_analyzer") String firstName } TestRepository类: package com.as.core.repositories import com.as.core.entities.Test import org.springframework.data.elasticsearch.repository.ElasticsearchRepository interface TestRepository extends ElasticsearchRepository<Test,String> { } 我的问题是如何从别名而不是索引本身读取? 解决方法
我通过在与对象关联的存储库类中使用ElasticsearchTemplate解决了这个限制(尽管如果有一种方法可以在实体本身上指定别名,那就更好了).
它的工作方式是创建自定义存储库接口.在你的情况下,它将是TestRepositoryCustom: public interface TestRepositoryCustom { Test> findByCustom(...); } 然后实现此接口,将“Impl”附加到基本存储库名称的末尾: public class TestRepositoryImpl implements TestRepositoryCustom { Page<Test> findByCustom(Pageable pageable,...) { BoolQueryBuilder boolQuery = new BoolQueryBuilder(); FilterBuilder filter = FilterBuilders.staticMethodsToBuildFilters; /* * Your code here to setup your query */ NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(boolQuery).withFilter(filter).withPageable(pageable); //These two are the crucial elements that will allow the search to look up based on alias builder.withIndices("test-alias"); builder.withTypes("test"); //Execute the query SearchQuery searchQuery = builder.build(); return elasticSearchTemplate.queryForPage(searchQuery,Test.class); } } 最后,在您的基础JPA repsitory接口TestRepository中,扩展TestRepositoryCustom接口,以便从您的存储库bean访问自定义接口上的任何方法. public interface TestRepository extends ElasticsearchRepository<Consultant,String>,TestRepositoryCustom { } 我真的希望看到的是对实体的注释,如: @Document(aliasName="test-alias") 这将在后台工作,以提供从门上搜索此索引,以便所有jpa查询都可以正常工作,无论索引名称如何. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |