/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_directory != null) { _directory.Close(); } }
/// <summary> /// Stores state to disk and closes all open resources. /// </summary> public void Close() { try { _iwriter.Close(); _directory.Close(); if (_searcher != null) { _searcher.Close(); } } catch (Exception ex) { logger.Error("Error closing database: {0}", ex.Message); } }
public void StoresPositionCorrectly() { analyzer = new MorphAnalyzer(HspellDict); indexDirectory = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexDirectory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED); string str = "קשת רשת דבשת מיץ יבשת יבלת גחלת גדר אינציקלופדיה חבר"; Document doc = new Document(); doc.Add(new Field("Text", str, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); searcher = new IndexSearcher(indexDirectory, true); RunQuery("\"קשת\"", 0); RunQuery("\"אינציקלופדיה\"", 8); RunQuery("\"חבר\"", 9); searcher.Close(); indexDirectory.Close(); }
/// <summary> /// 删除索引 /// </summary> public static bool Delete(int[] productIDList, bool needOptimize) { if (productIDList == null && productIDList.Length == 0) { return(false); } Lucene.Net.Store.Directory fsDir = FSDirectory.GetDirectory(PhysicalIndexDirectory, false); IndexReader reader = IndexReader.Open(fsDir); bool result = false; try { for (int i = 0; i < productIDList.Length; i++) { if (productIDList[i] != 0) { Term term = new Term(ProductIndexField.ProductID, productIDList[i].ToString()); reader.DeleteDocuments(term); } } reader.Close(); if (needOptimize) { IndexWriter fsWriter = new IndexWriter(fsDir, SearchHelper.GetChineseAnalyzer(), false); fsWriter.Optimize(); fsWriter.Close(); } result = true; } finally { fsDir.Close(); } return(result); }
/// <summary> Copy contents of a directory src to a directory dest. /// If a file in src already exists in dest then the /// one in dest will be blindly overwritten. /// /// <p/><b>NOTE:</b> the source directory cannot change /// while this method is running. Otherwise the results /// are undefined and you could easily hit a /// FileNotFoundException. /// /// <p/><b>NOTE:</b> this method only copies files that look /// like index files (ie, have extensions matching the /// known extensions of index files). /// /// </summary> /// <param name="src">source directory /// </param> /// <param name="dest">destination directory /// </param> /// <param name="closeDirSrc">if <code>true</code>, call {@link #Close()} method on source directory /// </param> /// <throws> IOException </throws> public static void Copy(Directory src, Directory dest, bool closeDirSrc) { System.String[] files = src.ListAll(); IndexFileNameFilter filter = IndexFileNameFilter.GetFilter(); byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE]; for (int i = 0; i < files.Length; i++) { if (!filter.Accept(null, files[i])) continue; IndexOutput os = null; IndexInput is_Renamed = null; try { // create file in dest directory os = dest.CreateOutput(files[i]); // read current file is_Renamed = src.OpenInput(files[i]); // and copy to dest directory long len = is_Renamed.Length(); long readCount = 0; while (readCount < len) { int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len?(int) (len - readCount):BufferedIndexOutput.BUFFER_SIZE; is_Renamed.ReadBytes(buf, 0, toRead); os.WriteBytes(buf, toRead); readCount += toRead; } } finally { // graceful cleanup try { if (os != null) os.Close(); } finally { if (is_Renamed != null) is_Renamed.Close(); } } } if (closeDirSrc) src.Close(); }
// LUCENE-1468 private void CheckDirectoryFilter(Directory dir) { System.String name = "file"; try { dir.CreateOutput(name).Close(); Assert.IsTrue(dir.FileExists(name)); Assert.IsTrue(new System.Collections.ArrayList(dir.ListAll()).Contains(name)); } finally { dir.Close(); } }
private RAMDirectory(Directory dir, bool closeDir) { System.String[] files = dir.List(); byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE]; for (int i = 0; i < files.Length; i++) { // make place on ram disk IndexOutput os = CreateOutput(System.IO.Path.GetFileName(files[i])); // read current file IndexInput is_Renamed = dir.OpenInput(files[i]); // and copy to ram disk long len = (int) is_Renamed.Length(); long readCount = 0; while (readCount < len) { int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len ? (int) (len - readCount) : BufferedIndexOutput.BUFFER_SIZE; is_Renamed.ReadBytes(buf, 0, toRead); os.WriteBytes(buf, toRead); readCount += toRead; } // graceful cleanup is_Renamed.Close(); os.Close(); } if (closeDir) dir.Close(); }
/// <summary> /// Loads the initial data. /// </summary> /// <param name="MetaDataTable">The meta data table.</param> public void LoadInitialData(DataTable MetaDataTable) { try { _contactsMetaDataTable = MetaDataTable; if (_writer != null) { _writer = null; } if (_analyzer != null) { _analyzer = null; } if (_directory != null) { _directory.Close(); _directory = null; } _analyzer = new StandardAnalyzer(Version.LUCENE_29); _directory = new RAMDirectory(); _writer = new IndexWriter(_directory, _analyzer, true); _writer.SetMergeScheduler(new SerialMergeScheduler()); int count = 1; DateTime date; foreach (DataRow dtRow in _contactsMetaDataTable.Rows) { Document _document = new Document(); foreach (DataColumn column in _contactsMetaDataTable.Columns) { try { DateTime chkDate; if (DateTime.TryParse(dtRow[column.ToString()].ToString(), out chkDate)) { if (chkDate != null) { if (!_contactAttributeDateFields.Contains(column.ColumnName)) { _contactAttributeDateFields.Add(column.ColumnName); } var numericField = new NumericField(column.ColumnName, count, Field.Store.YES, true); date = Convert.ToDateTime(dtRow[column.ToString()].ToString()); numericField.SetLongValue(long.Parse(date.ToString("yyyyMMddHHmmss"))); _document.Add(numericField); count++; } } else { if (_contactAttributeDateFields.Contains(column.ColumnName) && !string.IsNullOrEmpty(dtRow[column.ToString()].ToString())) { _contactAttributeDateFields.Remove(column.ColumnName); } Field stringField = new Field(column.ColumnName, dtRow[column.ToString()].ToString(), Field.Store.YES, Field.Index.ANALYZED); _document.Add(stringField); } } catch (Exception ex) { } } #region old //var numericStartDate = new NumericField("StartDate", count, Field.Store.YES, true); //date = Convert.ToDateTime(dtRow["StartDate"].ToString()); //numericStartDate.SetIntValue(int.Parse(date.ToString("yyyyMMddHHmmss"))); //var numericEndDate = new NumericField("EndDate", count, Field.Store.YES, true); //date = Convert.ToDateTime(dtRow["EndDate"].ToString()); //numericEndDate.SetIntValue(int.Parse(date.ToString("yyyyMMddHHmmss"))); //Field subject = new Field("Subject", dtRow["Subject"].ToString(), Field.Store.YES, Field.Index.ANALYZED); //Field mediaType = new Field("MediaType", dtRow["MediaType"].ToString(), Field.Store.YES, Field.Index.ANALYZED); //Field interactionID = new Field("InteractionId", dtRow["InteractionId"].ToString(), Field.Store.YES, Field.Index.ANALYZED); //Field contactId = new Field("ContactId", dtRow["ContactId"].ToString(), Field.Store.YES, Field.Index.ANALYZED); //Field status = new Field("Status", dtRow["Status"].ToString(), Field.Store.YES, Field.Index.ANALYZED); //_document.Add(subject); //_document.Add(mediaType); //_document.Add(interactionID); //_document.Add(contactId); //_document.Add(status); //_document.Add(numericStartDate); //_document.Add(numericEndDate); #endregion _writer.AddDocument(_document); } _writer.Commit(); _writer.Close(); } catch (Exception ex) { _logger.Error("Error while adding Initial Data : " + ex.InnerException == null ? ex.Message : ex.InnerException.Message); } }
public virtual void TestNorms() { // tmp dir System.String tempDir = System.IO.Path.GetTempPath(); if (tempDir == null) { throw new System.IO.IOException("java.io.tmpdir undefined, cannot run test"); } // test with a single index: index1 System.IO.DirectoryInfo indexDir1 = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempDir, "lucenetestindex1")); Directory dir1 = FSDirectory.Open(indexDir1); IndexWriter.Unlock(dir1); norms = new System.Collections.ArrayList(); modifiedNorms = new System.Collections.ArrayList(); CreateIndex(dir1); DoTestNorms(dir1); // test with a single index: index2 System.Collections.ArrayList norms1 = norms; System.Collections.ArrayList modifiedNorms1 = modifiedNorms; int numDocNorms1 = numDocNorms; norms = new System.Collections.ArrayList(); modifiedNorms = new System.Collections.ArrayList(); numDocNorms = 0; System.IO.DirectoryInfo indexDir2 = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempDir, "lucenetestindex2")); Directory dir2 = FSDirectory.Open(indexDir2); CreateIndex(dir2); DoTestNorms(dir2); // add index1 and index2 to a third index: index3 System.IO.DirectoryInfo indexDir3 = new System.IO.DirectoryInfo(System.IO.Path.Combine(tempDir, "lucenetestindex3")); Directory dir3 = FSDirectory.Open(indexDir3); CreateIndex(dir3); IndexWriter iw = new IndexWriter(dir3, anlzr, false, IndexWriter.MaxFieldLength.LIMITED); iw.SetMaxBufferedDocs(5); iw.MergeFactor = 3; iw.AddIndexesNoOptimize(new Directory[] { dir1, dir2 }); iw.Optimize(); iw.Close(); norms1.AddRange(norms); norms = norms1; modifiedNorms1.AddRange(modifiedNorms); modifiedNorms = modifiedNorms1; numDocNorms += numDocNorms1; // test with index3 VerifyIndex(dir3); DoTestNorms(dir3); // now with optimize iw = new IndexWriter(dir3, anlzr, false, IndexWriter.MaxFieldLength.LIMITED); iw.SetMaxBufferedDocs(5); iw.MergeFactor = 3; iw.Optimize(); iw.Close(); VerifyIndex(dir3); dir1.Close(); dir2.Close(); dir3.Close(); }
public override void Close() { _masterDirectory.Close(); _cacheDirectory.Close(); }
public override void TearDown() { dir.Close(); dir = null; base.TearDown(); }
/// <summary> Copy contents of a directory src to a directory dest. /// If a file in src already exists in dest then the /// one in dest will be blindly overwritten. /// /// </summary> /// <param name="src">source directory /// </param> /// <param name="dest">destination directory /// </param> /// <param name="closeDirSrc">if <code>true</code>, call {@link #close()} method on source directory /// </param> /// <throws> IOException </throws> public static void Copy(Directory src, Directory dest, bool closeDirSrc) { System.String[] files = src.List(); if (files == null) { throw new System.IO.IOException("cannot read directory " + src + ": list() returned null"); } byte[] buf = new byte[BufferedIndexOutput.BUFFER_SIZE]; for (int i = 0; i < files.Length; i++) { IndexOutput os = null; IndexInput is_Renamed = null; try { // create file in dest directory os = dest.CreateOutput(files[i]); // read current file is_Renamed = src.OpenInput(files[i]); // and copy to dest directory long len = is_Renamed.Length(); long readCount = 0; while (readCount < len) { int toRead = readCount + BufferedIndexOutput.BUFFER_SIZE > len ? (int) (len - readCount) : BufferedIndexOutput.BUFFER_SIZE; is_Renamed.ReadBytes(buf, 0, toRead); os.WriteBytes(buf, toRead); readCount += toRead; } } finally { // graceful cleanup try { if (os != null) os.Close(); } finally { if (is_Renamed != null) is_Renamed.Close(); } } } if (closeDirSrc) src.Close(); }
public virtual void TestDirectInstantiation() { System.IO.FileInfo path = new System.IO.FileInfo(SupportClass.AppSettings.Get("tempDir", System.IO.Path.GetTempPath())); int sz = 2; Directory[] dirs = new Directory[sz]; dirs[0] = new SimpleFSDirectory(path, null); // dirs[1] = new NIOFSDirectory(path, null); System.Console.WriteLine("Skipping NIOFSDirectory() test under Lucene.Net"); dirs[1] = new MMapDirectory(path, null); for (int i = 0; i < sz; i++) { Directory dir = dirs[i]; dir.EnsureOpen(); System.String fname = "foo." + i; System.String lockname = "foo" + i + ".lck"; IndexOutput out_Renamed = dir.CreateOutput(fname); out_Renamed.WriteByte((byte)i); out_Renamed.Close(); for (int j = 0; j < sz; j++) { Directory d2 = dirs[j]; d2.EnsureOpen(); Assert.IsTrue(d2.FileExists(fname)); Assert.AreEqual(1, d2.FileLength(fname)); // don't test read on MMapDirectory, since it can't really be // closed and will cause a failure to delete the file. if (d2 is MMapDirectory) { continue; } IndexInput input = d2.OpenInput(fname); Assert.AreEqual((byte)i, input.ReadByte()); input.Close(); } // delete with a different dir dirs[(i + 1) % sz].DeleteFile(fname); for (int j = 0; j < sz; j++) { Directory d2 = dirs[j]; Assert.IsFalse(d2.FileExists(fname)); } Lock lock_Renamed = dir.MakeLock(lockname); Assert.IsTrue(lock_Renamed.Obtain()); for (int j = 0; j < sz; j++) { Directory d2 = dirs[j]; Lock lock2 = d2.MakeLock(lockname); try { Assert.IsFalse(lock2.Obtain(1)); } catch (LockObtainFailedException e) { // OK } } lock_Renamed.Release(); // now lock with different dir lock_Renamed = dirs[(i + 1) % sz].MakeLock(lockname); Assert.IsTrue(lock_Renamed.Obtain()); lock_Renamed.Release(); } for (int i = 0; i < sz; i++) { Directory dir = dirs[i]; dir.EnsureOpen(); dir.Close(); Assert.IsFalse(dir.isOpen_ForNUnit); } }