How to index and search for a Datetime field in Lucene.NET?

I do not know how to index and search Registred_Date (it contains datetime sql format). I need to search between years or days. Where I use a boolean query to search. The code below is used for numeric fields and normal indexing of fields.

IndexWriter indexWriter = new IndexWriter(dir, new StandardAnalyzer(),Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED); DataSet ds = new DataSet(); //ds contains table if (ds.Tables[0] != null) { DataTable dt = ds.Tables[0]; if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { //Create the Document object Document doc = new Document(); foreach (DataColumn dc in dt.Columns) { string check = dc.ToString(); if (check.Equals("Experience")) { int n=Convert.ToInt32(dr[dc.ColumnName]); NumericField numericField = new NumericField(dc.ColumnName, Field.Store.YES, true); numericField.SetIntValue(n); doc.Add(numericField); } else if(check.Equals("Registred_Date")) { } else { doc.Add(new Field(dc.ColumnName, dr[dc.ColumnName].ToString(), Field.Store.YES, Field.Index.ANALYZED)); } //Populate the document with the column name and value from our query } // Write the Document to the catalog indexWriter.AddDocument(doc); } } } // Close the writer indexWriter.Close(); 
+6
source share
2 answers

Thanks @Thomas CG de Vilhena and Mihai Soloi. I found a solution with your help.

To index:

 DateTime d1 = Convert.ToDateTime(dr[dc.ColumnName]); doc.Add(new Field("Registered_Date", DateTools.DateToString(d1, DateTools.Resolution.SECOND), Field.Store.YES, Field.Index.ANALYZED)); 

For search:

 DateTime d1 = DateTime.Now.AddDays(-15); var dateValue = DateTools.DateToString(d1, DateTools.Resolution.MILLISECOND); var filter = FieldCacheRangeFilter.NewStringRange("Registered_Date",lowerVal: dateValue, includeLower: true,upperVal: null, includeUpper: false); 
+7
source

If you would save your index as a standard string, for example, if you convert from 2013-07-05 20:00:00 to 20130705200000 , you can use Lucene RangeQuery to search by ranges.

Sorry, I did not provide any sample code, but I am not familiar with the .NET API.

+1
source

Source: https://habr.com/ru/post/948842/


All Articles