7.4.4.2.5. FieldBridge
当将属性映射到 Lucene 索引时,有些用例需要不仅仅是简单的对象来字符串转换。为为您提供最大灵活性,您还可以将桥实施为 FieldBridge。此界面为您提供一个属性值,并允许您在 Lucene Document 中按照您想要的方式对其进行映射。例如,您可以在两个不同的文档字段中存储属性。接口的概念与 Hibernate 用户类型非常相似。
示例:实施 FieldBridge Interface
/**
* Store the date in 3 different fields - year, month, day - to ease Range Query 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;
在上面的示例中,这些字段不会直接添加到 Document 中。相反,添加被委派给 LuceneOptions 帮助程序;此帮助程序将应用您在 @Field( 如 Store 或 TermVector )上选择的选项,或应用所选的 @Boost 值。封装 COMPRESS 实施的复杂性特别有用。尽管建议将任何字段委派给 LuceneOptions 以向文档添加字段,但不会阻止您直接编辑文档,并在您需要时忽略 LuceneOptions。
注意
创建类似 LuceneOptions 的类,以方便您的应用程序免受 Lucene API 的变化,并简化您的代码。如果您愿意,请使用它们,但如果您需要更大的灵活性,则不需要.