我正在编写一个基于 Lucene 的过滤器:我有一些来自 API 的结果,我想强制这些结果匹配某个查询(API 有时不起作用)。由于结果是从 API 获得的,我基本上将它们存储在 RAM 中,对其进行索引和过滤。如果 Lucene 在我的索引中找到该文档,我认为该文档是可以的,如果不是,它将被过滤掉。
有时我希望它模糊,有时我不想。有一个近似开关。因此,我使用 StandardAnalyzer 进行近似 = false,并使用巴西分析器进行近似 = true。好的?
问题是巴西分析器近似否定项,我认为这不是一个好方法。例如,如果我需要“greve -trabalhadores”,则带有“greve do trabalho”的文档与查询匹配,但它不应该。如果我使用 StandardAnalyzer,它工作正常,如果我使用巴西分析器,它会忽略包含“trabalh”的所有内容,因为词干。
我的解决方案是使用 StandardAnalyzer 重写禁止的子句,它不会进行词干提取/模糊处理。因此,被禁止的查询部分,我将使用 StandardAnalyzer,另一部分将使用巴西分析器或 Standard(取决于近似开关)。
问题是它不起作用(有时)。
我的代码的一个小测试如下:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.br.BrazilianAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
public class Lucene {
private static Logger log = Logger.getLogger(Lucene.class.getName());
private String[] fields = new String[] { "title" };
private BrazilianAnalyzer analyzerBrazil = new BrazilianAnalyzer(Version.LUCENE_41, new CharArraySet(Version.LUCENE_41, Collections.emptyList(), true));
private StandardAnalyzer analyzerStandard = new StandardAnalyzer(Version.LUCENE_41, new CharArraySet(Version.LUCENE_41, Collections.emptyList(), true));
private MultiFieldQueryParser parserBrazil = new MultiFieldQueryParser(Version.LUCENE_41, fields , analyzerBrazil);
private MultiFieldQueryParser parserStandard = new MultiFieldQueryParser(Version.LUCENE_41, fields , analyzerStandard);
public void filter(String query, boolean fuzzy, List<Result> results) {
Directory index = null;
if (results == null || results.size() == 0) {
return;
}
try {
Analyzer analyzer = fuzzy ? analyzerBrazil : analyzerStandard;
Query q = fuzzy ? parserBrazil.parse(query) : parserStandard.parse(query);
// terms to ignore/prohibited shoudn't be fuzzyfied...
if (fuzzy) {
Query queryNoFuzzy = parserStandard.parse(query);
if (q instanceof BooleanQuery) {
BooleanClause[] clauses = ((BooleanQuery)queryNoFuzzy).getClauses();
if (clauses != null && clauses.length > 0) {
BooleanClause clause = null;
for (int i = 0; i < clauses.length; i++) {
clause = clauses[i];
if (clause.isProhibited()) {
((BooleanQuery)q).clauses().set(i, clause);
}
}
}
}
}
log.info(q.toString());
index = index(results, analyzer);
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(index));
TopDocs resultsFoundDocs = searcher.search(q, results.size());
List<Result> resultsFound = new ArrayList<Result>();
for (ScoreDoc resultadoFiltro : resultsFoundDocs.scoreDocs) {
log.info("Score " + resultadoFiltro.score);
resultsFound.add(results.get(Integer.parseInt(searcher.doc(resultadoFiltro.doc).get("index"))));
}
for (Result result : results) {
if (!resultsFound.contains(result)) {
result.setFiltered(true);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
index.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Directory index(List<Result> resultados, Analyzer analyzer) {
try {
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_41, analyzer);
IndexWriter writer = new IndexWriter(index, config);
indexResults(writer, analyzer, resultados);
return index;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void indexResults(IndexWriter w, Analyzer analyzer, List<Result> resultados) throws IOException {
try {
Document resultado = null;
for (int i = 0; i < resultados.size(); i++) {
resultado = new Document();
resultado.add(new TextField(fields[0], resultados.get(i).getTitle(), Field.Store.YES));
resultado.add(new IntField("index", i, Field.Store.YES));
w.addDocument(resultado, analyzer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
w.close();
}
}
public static void main(String[] args) {
List<Result> ocs = new ArrayList<Result>();
Result rb = new Result("Vivo Celular - não instalação do produto");
ocs.add(rb);
System.out.println("ITEMS ____________________________");
for (Result oc : ocs) {
System.out.println(oc.getTitle());
}
System.out.println("ITEMS ____________________________");
String query = "vivo -celular";
System.out.println("\n >> QUERY " + query);
new Lucene().filter(query, true, ocs);
System.out.println("\nFOUND ____________________________");
for (Result oc : ocs) {
if (!oc.getFiltered()) {
System.out.println(oc.getTitle());
}
}
System.out.println("FOUND ____________________________");
}
}
class Result {
private String title;
private Boolean filtered = false;
public Result(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getFiltered() {
return filtered;
}
public void setFiltered(Boolean filtered) {
this.filtered = filtered;
}
}
有一个简单的文档,标题为“Vivo Celular - não instalação do produto”。我将查询“vivo -celular”,因此,由于文档包含 celular,因此searcher.search(q, results.size())不应返回它;称呼。它仅在近似开关打开时发生,即使它打印查询以仅将“vivo”提取到“viv”(查询是“(title:viv)-(title:celular)”)。
那是对的吗???
我正在使用版本 4.2.2。它也发生在 4.1.0。
任何人都可以启发我吗?
提前谢谢了。