简体   繁体   中英

Deleting a document in apache lucene having exact match

I want to delete a document in apache lucene having exact match only. for example I have documents containing text:

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

And when Try to remove the document with query 'Bilal' it deletes all these three documents while it should delete just first document with exact match.

The Code I use is this:

    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();    

This is how I am indexing my documents:

    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);
            }
        }

You have missed to provide how you index those documents. If they are indexed using StandardAnalyzer and tokenization is on, it is understandable that you get these results - this is because StandardAnalyzer tokenizes the text for each word and since each of your documents contains Bilal , you hit all those documents as a result.

The general advice is that you should always add a unique id field and query/delete by this id field.

If you can't do this - index the same text as a separate field - without tokenization - and use phrase query to find the exact match, but this sounds like a horrible hack to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM