如何在索引期间为Hibernate搜索中的实体添加后缀和前缀?
我需要这个来执行精确的搜索。例如,如果搜索"this is a test",则会找到以下条目:* this is a test * this is a test and ...
因此,我找到了在索引期间向整个值添加前缀和后缀的想法,例如:_____ this is a test _____
如果要搜索"this is a test“并启用精确搜索的复选框,我将更改搜索字符串to_ "_____ this is a test _____”
我为此创建了一个FilterFactory,但对于这个term,它将前缀和后缀添加到每个术语:
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;
}
}
发布于 2017-02-20 19:07:25
这不是你应该怎么做的。
您需要的是将索引的字符串视为唯一的标记。这样,您将只得到具有确切令牌的结果。
为此,您需要定义一个基于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。
了解分析器的用途是很重要的,因为通常默认分析器并不完全是您要查找的分析器。
https://stackoverflow.com/questions/42342041
复制相似问题