Hibernate搜索突出显示未分析的字段

时间:2017-12-06 11:30:20

标签: java hibernate lucene hibernate-search

如果它们与搜索查询匹配,我想突出显示整个未分析的字段 索引实体如下所示:

@Entity
@Indexed
@AnalyzerDef(
        name = "documentAnalyzer",
        tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
        filters = {
                @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(
                        factory = StopFilterFactory.class,
                        params = {
                                @Parameter(name = "words", value = "stoplist.properties"),
                                @Parameter(name = "ignoreCase", value = "true")
                        }
                )
        }
)
public class Document {

    ...

    @Field(analyze = Analyze.NO)
    private String notAnalyzedField; // has "x-xxx-xxx" format

    @Field(analyze = Analyze.YES)
    private String analyzedField;   

}

假设我有一个Document notAnalyzedField: "a-bbb-ccc",然后我运行一个具有相同值的搜索查询,并使用以下代码突出显示搜索结果:

String highlightText(Query query, Analyzer analyzer, String fieldName, String text) {
    QueryScorer queryScorer = new QueryScorer(query);
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span>", "</span>");
    Highlighter highlighter = new Highlighter(formatter, queryScorer);
    return highlighter.getBestFragment(analyzer, fieldName, text);
}

因此,我得到以下代码段:"a-<span>bbb</span>-<span>ccc</span>" 这似乎是合理的,因为分析器将a符号视为停用词并将-视为分隔符并且不突出显示它们。但我无法弄清楚如何在突出显示此字段时避免使用分析器。 Highlighter课程中有一些方法需要TokenStream而不是Analyzer,但我不确定如何使用它们。

我想要实现的结果是整个突出显示的字段:"<span>a-bbb-ccc</span>"
有没有办法用hibernate-search来实现这个目标?

1 个答案:

答案 0 :(得分:1)

您的分析仪来自哪里?

您可能希望从Hibernate Search获取它:

FullTextEntityManager em = /*...*/;
Analyzer analyzer = em.getSearchFactory()
    .getAnalyzer(Document.class);
highlightText(query, analyzer, fieldName, text);

如果不起作用,请尝试使用KeywordAnalyzerhighlightText(query, new KeywordAnalyzer(), fieldName, text);