【问题标题】:Deleting a document in apache lucene having exact match删除具有完全匹配的apache lucene中的文档
【发布时间】:2014-01-03 02:40:17
【问题描述】:

我想删除 apache lucene 中只有完全匹配的文档。例如我有包含文本的文档:

  Document1: Bilal
  Document2: Bilal Ahmed
  Doucument3: Bilal Ahmed - 54

当尝试使用查询“Bilal”删除文档时,它会删除所有这三个文档,而它应该只删除第一个完全匹配的文档。

我使用的代码是这样的:

    String query = "bilal";
    String field = "userNames";

    Term term = new Term(field, query);

    IndexWriter indexWriter = null;

    File indexDir = new File(idexedDirectory);
    Directory directory = FSDirectory.open(indexDir);

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_46, analyzer);

    indexWriter = new IndexWriter(directory, iwc);        

    indexWriter.deleteDocuments(term);
    indexWriter.close();    

这就是我索引文档的方式:

    File indexDir = new File("C:\\Local DB\\TextFiled");
    Directory directory = FSDirectory.open(indexDir);

    Analyzer  analyzer = new StandardAnalyzer(Version.LUCENE_46);
    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_46, analyzer);              

   //Thirdly We tell the Index Writer that which document to index
   indexWriter = new IndexWriter(directory, iwc);

    int i = 0;

    try (DataSource db = DataSource.getInstance()) {

        PreparedStatement ps = db.getPreparedStatement(
                "SELECT user_id, username FROM " + TABLE_NAME + " as au" + User_CONDITION);

        try (ResultSet resultSet = ps.executeQuery()) {

            while (resultSet.next()) {
                i++;
                doc = new Document();

                text = resultSet.getString("username");                    
                doc.add(new StringField("userNames", text, Field.Store.YES));

                indexWriter.addDocument(doc);
                System.out.println("User Name : " + text + " : " + userID);
            }
        }

【问题讨论】:

  • 我还有一个问题,我在文档中添加了一个整数字段,例如 userID,例如: Document doc = new Document(); doc.add(doc.add(new IntField("userID", userID, Field.Store.YES)); 现在,如果我想搜索 id 为 1000 的文档,那么我将如何进行查询? String query = " 1000" 或其他方式?

标签: java lucene


【解决方案1】:

您没有提供如何索引这些文档。如果它们使用StandardAnalyzer 进行索引并且标记化已打开,那么您得到这些结果是可以理解的——这是因为StandardAnalyzer 标记了每个单词的文本,并且由于您的每个文档都包含Bilal,因此您点击了所有这些文档结果。

一般建议是您应该始终添加一个唯一的 id 字段并通过此 id 字段查询/删除。

如果您不能这样做 - 将相同的文本索引为单独的字段 - 无需标记化 - 并使用短语查询来查找完全匹配,但这对我来说听起来像是一个可怕的黑客攻击。

【讨论】:

  • 感谢您的建议。我试试这个,让你知道是否有任何进一步的问题。再次感谢
  • 我也提到了我如何索引我的文档。
  • 我还有一个问题,如果我使用您的第二个选项,即在文档中添加了一个整数字段,例如 userID,例如: Document doc = new Document(); doc.add(doc.add(new IntField("userID", userID, Field.Store.YES)); 现在,如果我想搜索 id 为 1000 的文档,那么我将如何进行查询? String query = " 1000" 或其他方式?
  • 查询将是userID:1000
  • like String query = "userID:1000" ?
猜你喜欢
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多