首页 > 解决方案 > Hibernate Search [5.11.5.Final] 动态数字属性:无法自动确定字段“...”的字段类型

问题描述

我在正确索引动态数字字段时遇到了一些麻烦,似乎它们总是被索引为字符串。

据我了解,在索引动态数字字段时,我必须使用动态模板:

PUT /com.product.product

{
    "mappings": {
        "com.product.Product": {
            "dynamic_templates": [
                {
                    "numeric_sort": {
                        "match_mapping_type": "*",
                        "match_pattern": "regex",
                        "match": "^sort_num_.*",
                        "mapping": {
                            "type": "double"
                        }
                    }
                }
            ]
        }
    }
}

我在事件监听器中上传:

@Configuration
@Transactional
public abstract class DynamicTemplateConfig {
    @EventListener
    public void addDynamicTemplates(ContextRefreshedEvent event) {
        if (this.searchIndexingIsActive) {
            this.addDynamicTemplates();
        }
    }
    ...
}

我正在索引字段桥中的属性:

public class PropertyValueFieldBridge implements FieldBridge {
    ...
    private void indexBigDecimalProperties(Document document, LuceneOptions luceneOptions, PropertyBigDecimal property) {
            String fieldName = PREFIX_SORT + NUMERIC + DELIMITER + property.getProperty().getCode();
            Double indexedValue = property.getValue().doubleValue();
    
            luceneOptions.addNumericFieldToDocument(
                    fieldName,
                    indexedValue,
                    document);
        }

    }

在索引这些 BigDecimal 属性后,我总是以索引的字符串属性结束:

"_source": {
    "id": "1",
    "sort_id": 1,
    "filter_id": 1,
    "sort_num_quantity": "115.0"
}

当我尝试对该属性进行排序时,出现以下异常:

org.hibernate.search.exception.SearchException: Cannot automatically determine the field type for field 'sort_num_quantity'. Use byField(String, Sort.Type) to provide the sort type explicitly.
    at org.hibernate.search.query.dsl.sort.impl.SortFieldStates.getCurrentSortFieldTypeFromMetamodel(SortFieldStates.java:177) ~[hibernate-search-engine-5.11.5.Final.jar:5.11.5.Final]
    at org.hibernate.search.query.dsl.sort.impl.SortFieldStates.determineCurrentSortFieldTypeAutomaticaly(SortFieldStates.java:150) ~[hibernate-search-engine-5.11.5.Final.jar:5.11.5.Final]
    at org.hibernate.search.query.dsl.sort.impl.ConnectedSortContext.byField(ConnectedSortContext.java:42) ~[hibernate-search-engine-5.11.5.Final.jar:5.11.5.Final]

我试图避免使用,byField(String, Sort.Type)因为它需要明确验证每个属性,我可能不知道名称和类型。

我在索引过程中做错了吗?

提前致谢

标签: javaspring-boothibernateelasticsearchhibernate-search

解决方案


我不认为你做错了什么。Hibernate Search 5 中的实验性 Elasticsearch 集成并不真正支持动态字段。您不能提前指定字段的类型,并且它显然默认为动态字段的 String 类型。

升级到 Hibernate Search 6(目前处于候选发布阶段)将是一个解决方案,因为它通过字段模板支持动态字段 然而,Hibernate Search 6 API 不同,因此迁移可能需要大量工作。


推荐阅读