【发布时间】:2021-11-05 03:36:19
【问题描述】:
我们需要从一个数据属性索引不同的字段。这已通过实现 FieldBridge 并在那里添加字段来解决。 从 hibernate 搜索参考的这个例子中可以看出:
/**
* Store the date in 3 different fields - year, month, day - to ease the creation of RangeQuery per
* year, month or day (eg get all the elements of December for the last 5 years).
* @author Emmanuel Bernard
*/
public class DateSplitBridge implements FieldBridge {
private final static TimeZone GMT = TimeZone.getTimeZone("GMT");
public void set(String name, Object value, Document document,
LuceneOptions luceneOptions) {
Date date = (Date) value;
Calendar cal = GregorianCalendar.getInstance(GMT);
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
// set year
luceneOptions.addFieldToDocument(
name + ".year",
String.valueOf( year ),
document );
// set month and pad it if needed
luceneOptions.addFieldToDocument(
name + ".month",
month < 10 ? "0" : "" + String.valueOf( month ),
document );
// set day and pad it if needed
luceneOptions.addFieldToDocument(
name + ".day",
day < 10 ? "0" : "" + String.valueOf( day ),
document );
}
}
//property
@FieldBridge(impl = DateSplitBridge.class)
private Date date;
除了上面的例子,我们将我们的设置为 twoWayFieldBridge:
public class DateSplitBridge implements TwoWayFieldBridge {
[...]
@Override
public Object get(String name, Document document) {
final IndexableField field = document.getField(name);
if (field != null) {
return field.stringValue();
} else {
return null;
}
}
@Override
public String objectToString(Object object) {
return object.toString();
}
问题是,当搜索通过 FieldBridge 定义的字段之一时,搜索似乎不知道它:
原因:org.hibernate.search.exception.SearchException:无法 在 [...] 中查找字段 date.day org.hibernate.search.engine.spi.DocumentBuilderIndexedEntity.objectToString(DocumentBuilderIndexedEntity.java:1052)
如果字段被映射(每个注释或 API),则不会发生错误:
//property
@Fields({@Field(name="date.day", bridge = @FieldBridge(impl=DateSplitBridge.class)),
@Field(name="date.month", bridge = @FieldBridge(impl=DateSplitBridge.class)),
@Field(name="date.year", bridge = @FieldBridge(impl=DateSplitBridge.class))})
private Date date;
但是在索引时出现错误,因为该字段随后在映射中定义,而导致此问题的 FieldBridge:
2021-09-08 08:42:50,063 错误 org.hibernate.search.exception.impl.LogErrorHandler:71 - HSEARCH000058:HSEARCH000183:无法索引类型的实例 [...] java.lang.IllegalArgumentException: DocValuesField "date.day" 出现不止一次 此文档(每个字段只允许一个值)在 org.apache.lucene.index.SortedDocValuesWriter.addValue(SortedDocValuesWriter.java:62) ...
应该如何处理?我们如何将 FieldBridge 中的字段传播到搜索,以使它们首先可搜索?
【问题讨论】:
标签: java hibernate indexing lucene hibernate-search