14.2.4.2.5. FieldBridge
場合によっては、プロパティーを Lucene インデックスにマッピングするときに、単純なオブジェクトから文字列への変換が必要になります。可能な限り柔軟性を持たせるために、
FieldBridge としてブリッジを実装することもできます。このインターフェースは、プロパティーの値を提供し、Lucene Document 内で希望する方法でマッピングできるようにします。たとえば、プロパティーを異なるドキュメントフィールドに保存できます。インターフェースの概念は Hibernate UserType と非常に似ています。
例14.28 FieldBridge インターフェイスの実装
/**
* 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;
の例14.28「FieldBridge インターフェイスの実装」フィールドはドキュメントに直接追加されません。代わりに、追加が
LuceneOptions ヘルパーシステムに委任されます。このヘルパーは、Store や TermVector などの @Fieldで選択したオプションを適用するか、選択した @Boost 値を適用します。COMPRESS 実装の複雑性をカプセル化することは特に便利です。Document にフィールドを追加するために LuceneOptions に委譲することが推奨されますが、必要であれば、Document を直接編集して、LuceneOptions を無視しても問題ありません。
注記
LuceneOptions などのクラスは、アプリケーションを Lucene API の変更から保護し、コードを簡素化するために作成されます。可能な場合はこれを使用しますが、さらに柔軟性が必要な場合は、使用しなくても問題ありません。