使用Hibernate Search自动完成

时间:2011-03-19 12:04:54

标签: java mysql hibernate autocomplete hibernate-search

我正在尝试为我的网站构建更好的自动完成功能。我想使用Hibernate Search来做这个,但就我实验而言,它只为我找到了完整的单词。

所以,我的问题是:是否可以仅搜索某些字符?

例如。用户输入3个字母并使用休眠搜索向他显示我的db对象的所有单词,其中包含这3个字母?

PS。现在我正在使用“喜欢”的查询...但我的数据库增长了很多,我还希望将搜索功能扩展到另一个表...

3 个答案:

答案 0 :(得分:12)

主要修改 一年后,我能够改进我发布的原始代码来生成这个:

我的索引实体:

@Entity
@Indexed
@AnalyzerDef(name = "myanalyzer",
// Split input into tokens according to tokenizer
tokenizer = @TokenizerDef(factory = WhitespaceTokenizerFactory.class), //
filters = { //
// Normalize token text to lowercase, as the user is unlikely to care about casing when searching for matches
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
// Index partial words starting at the front, so we can provide Autocomplete functionality
@TokenFilterDef(factory = NGramFilterFactory.class, params = { @Parameter(name = "maxGramSize", value = "1024") }),
// Close filters & Analyzerdef
})
@Analyzer(definition = "myanalyzer")
public class Compound extends DomainObject {
public static String[] getSearchFields(){...}
...
}

所有@Field都被标记化并存储在索引中;这需要工作:
@Field(index = Index.TOKENIZED, store = Store.YES)

@Transactional(readOnly = true)
public synchronized List<String> getSuggestions(final String searchTerm) {
    // Compose query for term over all fields in Compound
    String lowerCasedSearchTerm = searchTerm.toLowerCase();

    // Create a fullTextSession for the sessionFactory.getCurrentSession()
    FullTextSession fullTextSession = Search.getFullTextSession(getSession());

    // New DSL based query composition
    SearchFactory searchFactory = fullTextSession.getSearchFactory();
    QueryBuilder buildQuery = searchFactory.buildQueryBuilder().forEntity(Compound.class).get();
    TermContext keyword = buildQuery.keyword();
    WildcardContext wildcard = keyword.wildcard();
    String[] searchfields = Compound.getSearchfields();
    TermMatchingContext onFields = wildcard.onField(searchfields[0]);
    for (int i = 1; i < searchfields.length; i++)
        onFields.andField(searchfields[i]);
    TermTermination matching = onFields.matching(input.toLowerCase());
    Query query = matching.createQuery();

    // Convert the Search Query into something that provides results: Specify Compound again to be future proof
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, Compound.class);
    fullTextQuery.setMaxResults(20);

    // Projection does not work on collections or maps which are indexed via @IndexedEmbedded
    List<String> projectedFields = new ArrayList<String>();
    projectedFields.add(ProjectionConstants.DOCUMENT);
    List<String> embeddedFields = new ArrayList<String>();
    for (String fieldName : searchfields)
        if (fieldName.contains("."))
            embeddedFields.add(fieldName);
        else
            projectedFields.add(fieldName);

    @SuppressWarnings("unchecked")
    List<Object[]> results = fullTextQuery.setProjection(projectedFields.toArray(new String[projectedFields.size()])).list();

    // Keep a list of suggestions retrieved by search over all fields
    List<String> suggestions = new ArrayList<String>();
    for (Object[] projectedObjects : results) {
        // Retrieve the search suggestions for the simple projected field values
        for (int i = 1; i < projectedObjects.length; i++) {
            String fieldValue = projectedObjects[i].toString();
            if (fieldValue.toLowerCase().contains(lowerCasedSearchTerm))
                suggestions.add(fieldValue);
        }

        // Extract the search suggestions for the embedded fields from the document
        Document document = (Document) projectedObjects[0];
        for (String fieldName : embeddedFields)
            for (Field field : document.getFields(fieldName))
                if (field.stringValue().toLowerCase().contains(lowerCasedSearchTerm))
                    suggestions.add(field.stringValue());
    }

    // Return the composed list of suggestions, which might be empty
    return suggestions;
}

我在最后处理@IndexedEmbedded字段时遇到了一些争吵。如果你没有这些,你可以简化代码,只是简单地投射搜索字段,并省略文档&amp; embeddedField handling。

和以前一样: 希望这对下一个遇到这个问题的人有用。如果有人对上述代码有任何批评或改进,请随时编辑,请告诉我。


Edit3 :此代码取自的项目自开源以来;以下是相关课程:

https://trac.nbic.nl/metidb/browser/trunk/metidb/metidb-core/src/main/java/org/metidb/domain/Compound.java
https://trac.nbic.nl/metidb/browser/trunk/metidb/metidb-core/src/main/java/org/metidb/dao/CompoundDAOImpl.java
https://trac.nbic.nl/metidb/browser/trunk/metidb/metidb-search/src/main/java/org/metidb/search/text/Autocompleter.java

答案 1 :(得分:7)

您可以使用建议NGramFilterhere为该字段建立索引。为了获得最佳效果,您应该使用Apache Solr中的EdgeNgramFilter,它从术语的起始边缘创建ngrams,也可以用于休眠搜索。

答案 2 :(得分:2)

蒂姆的回答很棒,帮助我克服了困难的部分。它只适用于我的单个单词查询。如果有人希望它使其适用于短语搜索。只需将所有'Term'实例替换为相应的'Phrase'类。以下是蒂姆代码的替换线,为我提供了诀窍。

// New DSL based query composition
            //org.hibernate.search.query.dsl
            SearchFactory searchFactory = fullTextSession.getSearchFactory();
            QueryBuilder buildQuery = searchFactory.buildQueryBuilder().forEntity(MasterDiagnosis.class).get();
            PhraseContext keyword = buildQuery.phrase();
            keyword.withSlop(3);
            //WildcardContext wildcard = keyword.wildcard();
            String[] searchfields = MasterDiagnosis.getSearchfields();
            PhraseMatchingContext onFields = keyword.onField(searchfields[0]);
            for (int i = 1; i < searchfields.length; i++)
                onFields.andField(searchfields[i]);
            PhraseTermination matching = onFields.sentence(lowerCasedSearchTerm);
            Query query = matching.createQuery();
 // Convert the Search Query into something that provides results: Specify Compound again to be future proof