首页 > 解决方案 > 如何返回在索引中获得命中的查询词

问题描述

我正在尝试返回导致我的 Lucene 索引命中的原始术语。例如,我的搜索字符串是“The quick brown fox jumps over the lazy dog”。“狗”这个词在索引中很受欢迎,比如“狗带”“遛狗”。同样,“fox”也有“fox glove”“foxy loxi”等热门歌曲。

所以,我想为用户打印出原始的“快速棕色狐狸”字符串,其中突出显示了命中(狗和狐狸)的术语。有几个例子,比如 Getmatched terms in query使用 explain 方法,但答案并没有走到最后一步。我认为 Lucene 不会轻易做到这一点,我将不得不使用正则表达式。

标签: lucene

解决方案


我想出了一种方法来生成一个字符串,该字符串是带有突出显示的命中术语的原始用户文本。以通常的方式针对索引查询原始用户文本。原始用户文本和结果被传递给“反向”查询方法。即:将原始用户文本转化为基于内存的索引,通过原始结果进行查询。这与我们最初所做的相反。结果是将结果中的常用词与字符串进行比较。这在我的索引中有效,因为所有结果都是“严格”定义。

荧光笔用于在原始结果中找到的常用词 [..] 周围插入分隔符。正则表达式 (?<=\[)(.*?)(?=\]) 用于使用分隔符删除单个找到的单词。

个人找到的单词和原始用户文本被传递给以下方法,该方法删除重复项并突出显示用户原始字符串中的单词:

//remove found term duplicates and produce a single string with all the hits highlighted

私有静态无效 removeTermDuplicates(列表 textResult,字符串 searchText){

// to be the final modified string with all highlights
String strOutput = searchText;

// creating a hashset using the incoming list
Set<String> textSet = new LinkedHashSet<String>(textResult);
// remove all the elements from the list 
textResult.clear();
// add all the elements of the set to create a

// list of found terms without duplicates
textResult.addAll(textSet);

// add html elements to found terms
for(String term : textResult){
    replacementWord.add("<b>"+term+"</b>");
}
//put original term and the same term with highlights in a hash map
for(int i=0; i<replacementWord.size(); ++i) {
    oldAndNewTerms.put(textResult.get(i), replacementWord.get(i));

}

//use a hash map to modify the original string
for (String key : oldAndNewTerms.keySet()){       

      strOutput = strOutput.replace(key,oldAndNewTerms.get(key) );      }

System.out.println(strOutput);

}

希望这对将来的某人有所帮助。菲尔


推荐阅读