2017-02-20 103 views
0

如何在編制索引期間在Hibernate搜索中爲實體添加後綴和前綴?如何在編制索引時添加前綴和後綴

我需要這個來執行精確搜索。 例如如果一個搜索「這是一個測試」,然後輸入以下內容中找到: *這是一個測試 *這是一個測試,...

所以我認爲這個想法添加一個前綴和後綴來索引在整個值,例如: _____這是一個測試_____

,如果一個搜索「這是一個考驗」,併爲實現精確搜索的複選框,我會改變搜索字符串to_ 「 _____這是一個測試_____「

我爲此創建了一個FilterFactory,但是使用這個FilterFactory爲每個術語添加了前綴和後綴:

public boolean incrementToken() throws IOException { 
     if (!this.input.incrementToken()) { 
      return false; 
     } else { 
      String input = termAtt.toString(); 
      // add "_____" at the beginning and ending of the phrase for exact match searching 
      input = "_____ " + input + " _____"; 
      char[] newBuffer = input.toLowerCase().toCharArray(); 
      termAtt.setEmpty(); 
      termAtt.copyBuffer(newBuffer, 0, newBuffer.length); 
      return true; 
     } 
    } 

回答

2

這不是你應該怎麼做的。

你需要的是你索引的字符串被認爲是一個唯一的標記。這樣,你只會得到具有確切令牌的結果。

爲此,您需要根據KeywordTokenizer定義分析器。

@Entity 
@AnalyzerDefs({ 
    @AnalyzerDef(name = "keyword", 
     tokenizer = @TokenizerDef(factory = KeywordTokenizerFactory.class) 
    ) 
}) 
@Indexed 
public class YourEntity { 
    @Fields({ 
     @Field, // your default field with default analyzer if you need it 
     @Field(name = "propertyKeyword", analyzer = @Analyzer(definition = "keyword")) 
    }) 
    private String property; 
} 

然後你應該搜索propertyKeyword字段。請注意,分析器定義是全局性的,因此您只需聲明一個實體的定義以使其可用於所有實體。

查看有關分析儀的文檔:http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#example-analyzer-def

瞭解分析儀的用途很重要,因爲通常默認的分析儀並不是您正在尋找的分析儀。

+0

完美,非常感謝您的幫助 - 我從中學到了一些新東西 – occurred