namespace ConsoleApplication2
{

using Lucene.Net.Store;
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.Analysis.Standard;
using Newtonsoft.Json.Linq;
using Lucene.Net.Documents;
using Lucene.Net.Util;
using System;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// TODO: Update summary.
/// </summary>
public class LuceneManager
{
private FSDirectory directory = null;
private Analyzer analyzer = null;
private QueryParser parser = null;
private IndexSearcher searcher = null;
private volatile bool searcherhastoupdate = false;

private object syncLock = null;
private object scsyncLock = null;
private LuceneManager me = null;

static LuceneManager()
{

}

public LuceneManager(string directory)
{
this.syncLock = new object();
this.scsyncLock = new object();
this.directory = FSDirectory.GetDirectory(directory);
this.analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
}

private Document CreateDocument(JObject jsonObject)
{
Document doc = new Document();

foreach (var item in jsonObject.Properties())
{
doc.Add(new Field(item.Name,
jsonObject[item.Name].ToString(),
Field.Store.YES,
Field.Index.ANALYZED));
}

return doc;
}

public void AddDocument(params JObject[] objects)
{
try
{
lock (syncLock)
{
IndexWriter writer = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);

foreach (var item in objects)
{
writer.AddDocument(this.CreateDocument(item));
}

writer.Optimize();

writer.Close();

searcherhastoupdate = true;
}
}
catch (Exception ex)
{

throw;
}
}

public void UpdateDocument(params JObject[] objects)
{
try
{
lock (syncLock)
{
IndexModifier modifier = new IndexModifier(directory, analyzer, false);

foreach (var item in objects)
{
int i = modifier.DeleteDocuments(new Term("id", Convert.ToString(item["id"])));
modifier.AddDocument(this.CreateDocument(item));
}

modifier.Optimize();

modifier.Close();

searcherhastoupdate = true;
}
}
catch (Exception ex)
{

throw;
}
}

public List<Document> Search(string field, string query, int n)
{
List<Document> docs = new List<Document>();
this.parser = new QueryParser(field, analyzer);
ScoreDoc[] hits = null;

nullsearch:

if (searcher == null || searcherhastoupdate == true)
{
lock (syncLock)
{
if (searcher == null || searcherhastoupdate == true)
{
searcher = new IndexSearcher(directory);
}
}
}

hits = searcher.Search(parser.Parse(query), null, n).ScoreDocs;

if (hits.Length == 0)
return null;

for (int i = 0; i < hits.Length; i++)
{
docs.Add(searcher.Doc(hits[i].doc));
}

return docs;
}
}
}

Last edited Nov 30, 2012 at 8:46 PM by kirubasankars, version 1

Comments

No comments yet.