首页 > 解决方案 > 如何在 JSON 对象属性上动态创建索引(JSON 对象道具也是动态的)

问题描述

我有一个场景,我想在 JSON 对象的键上动态创建索引(JSON 对象属性会有所不同)。我能够将 JSON 对象存储为索引(通过实现FieldBridge)。

eg1: preference:{"sport":"football", "music":"pop")
eg2: preference:{"sport":"cricket", "music":"jazz", "cuisine":"mexican"}

但我无法查询单个字段,例如: preference.sportpreference.cuisine

休眠搜索中是否有任何方法/配置可以实现这一目标?

标签: hibernate-search

解决方案


If your fields are dynamic, there is no pre-defined schema and Hibernate Search is unable to determine how to query these fields. There are significant differences in how a match query should be executed on a text field or a date field, for example.

For that reason, you cannot use the Hibernate Search Query DSL to build your queries.

However, you can use native APIs.

If you're using the Lucene integration, just creating the relevant queries yourself will work fine (as long as you create the right one):

new TermQuery(new Term("sport", "value"))

If you're using the experimental Elasticsearch integration, you can use org.hibernate.search.elasticsearch.ElasticsearchQueries.fromJson( ... ). You will have to write the whole query as JSON, though, and will not be able to take advantage of the Hibernate Search QueryBuilder at all, even for queries on statically defined fields. See https://docs.jboss.org/hibernate/search/5.11/reference/en-US/html_single/#_queries

Better support for native queries, as well as dynamic fields with pre-defined types, which would be targetable in the Query DSL, is planned for Hibernate Search 6, but it's not there yet. See HSEARCH-3273.


推荐阅读