Parse() public method

Parses a query string, returning a {@link Lucene.Net.Search.Query}.
public Parse ( String query ) : Query
query String the query string to be parsed. ///
return Lucene.Net.Search.Query
Ejemplo n.º 1
0
        public void CustomBridges()
        {
            Cloud cloud = new Cloud();
            cloud.CustomFieldBridge = ("This is divided by 2");
            cloud.CustomStringBridge = ("This is div by 4");
            ISession s = OpenSession();
            ITransaction tx = s.BeginTransaction();
            s.Save(cloud);
            s.Flush();
            tx.Commit();

            tx = s.BeginTransaction();
            IFullTextSession session = Search.CreateFullTextSession(s);
            QueryParser parser = new QueryParser("id", new SimpleAnalyzer());

            Lucene.Net.Search.Query query = parser.Parse("CustomFieldBridge:This AND CustomStringBridge:This");
            IList result = session.CreateFullTextQuery(query).List();
            Assert.AreEqual(1, result.Count, "Properties not mapped");

            query = parser.Parse("CustomFieldBridge:by AND CustomStringBridge:is");
            result = session.CreateFullTextQuery(query).List();
            Assert.AreEqual(0, result.Count, "Custom types not taken into account");

            s.Delete(s.Get(typeof(Cloud), cloud.Id));
            tx.Commit();
            s.Close();
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Searches the index with the specified query text
 /// </summary>
 /// <param name="querytext">Text to search the index</param>
 /// <returns></returns>
 static public TopDocs SearchIndex(string querytext, out double time)
 {
     start     = DateTime.Now;
     querytext = querytext.ToLower();
     char[] splitters = new char[] { '\t', '\'', '-', '(', ')', ',', '’', '\n', ':', ';', '?', '.', '!', '*' };
     foreach (var s in splitters)
     {
         querytext = querytext.Replace(s.ToString(), string.Empty);
     }
     try
     {
         Query   query   = parser.Parse(querytext);
         TopDocs results = searcher.Search(query, 100);
         end  = DateTime.Now;
         time = (end - start).TotalMilliseconds;
         return(results);
     }
     catch
     {
         string onlyLetters = new string(querytext.Where(char.IsLetter).ToArray());
         if (onlyLetters.Length == 0)
         {
             onlyLetters = "asdfghjklzxcvbnmqwertyuiop";
         }
         Query   query   = parser.Parse(onlyLetters);
         TopDocs results = searcher.Search(query, 100);
         end  = DateTime.Now;
         time = (end - start).TotalMilliseconds;
         return(results);
     }
     //time = (end - start).TotalMilliseconds;
     //return;
 }
        public void ClassBridge()
        {
            ISession s = this.OpenSession();
            ITransaction tx = s.BeginTransaction();
            s.Save(this.getDept1());
            s.Save(this.getDept2());
            s.Save(this.getDept3());
            s.Flush();
            tx.Commit();

            tx = s.BeginTransaction();
            IFullTextSession session = Search.CreateFullTextSession(s);

            // The branchnetwork field is the concatenation of both
            // the branch field and the network field of the Department
            // class. This is in the Lucene document but not in the
            // Department entity itself.
            QueryParser parser = new QueryParser("branchnetwork", new SimpleAnalyzer());

            Query query = parser.Parse("branchnetwork:layton 2B");
            IFullTextQuery hibQuery = session.CreateFullTextQuery(query, typeof(Department));
            IList result = hibQuery.List();
            Assert.IsNotNull(result);
            Assert.AreEqual("2B", ((Department)result[0]).Network, "incorrect entity returned, wrong network");
            Assert.AreEqual("Layton", ((Department)result[0]).Branch, "incorrect entity returned, wrong branch");
            Assert.AreEqual(1, result.Count, "incorrect number of results returned");

            // Partial match.
            query = parser.Parse("branchnetwork:3c");
            hibQuery = session.CreateFullTextQuery(query, typeof(Department));
            result = hibQuery.List();
            Assert.IsNotNull(result);
            Assert.AreEqual("3C", ((Department)result[0]).Network, "incorrect entity returned, wrong network");
            Assert.AreEqual("West Valley", ((Department)result[0]).Branch, "incorrect entity returned, wrong branch");
            Assert.AreEqual(1, result.Count, "incorrect number of results returned");

            // No data cross-ups .
            query = parser.Parse("branchnetwork:Kent Lewin");
            hibQuery = session.CreateFullTextQuery(query, typeof(Department));
            result = hibQuery.List();
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count == 0, "problem with field cross-ups");

            // Non-ClassBridge field.
            parser = new QueryParser("BranchHead", new SimpleAnalyzer());
            query = parser.Parse("BranchHead:Kent Lewin");
            hibQuery = session.CreateFullTextQuery(query, typeof(Department));
            result = hibQuery.List();
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count == 1, "incorrect entity returned, wrong branch head");
            Assert.AreEqual("Kent Lewin", ((Department)result[0]).BranchHead, "incorrect entity returned");

            // Cleanup
            foreach (object element in s.CreateQuery("from " + typeof(Department).FullName).List())
            {
                s.Delete(element);
            }
            tx.Commit();
            s.Close();
        }
Ejemplo n.º 4
0
 private static Query ParseQuery(string searchQuery, QueryParser parser)
 {
     Query query;
     try
     {
         query = parser.Parse(searchQuery.Trim());
     }
     catch (ParseException)
     {
         query = parser.Parse(QueryParser.Escape(searchQuery.Trim()));
     }
     return query;
 }
Ejemplo n.º 5
0
        public void List()
        {
            IFullTextSession s = Search.CreateFullTextSession(OpenSession());
            ITransaction tx = s.BeginTransaction();
            Clock clock = new Clock(1, "Seiko");
            s.Save(clock);
            clock = new Clock(2, "Festina");
            s.Save(clock);
            Book book =
                new Book(1, "La chute de la petite reine a travers les yeux de Festina",
                         "La chute de la petite reine a travers les yeux de Festina, blahblah");
            s.Save(book);
            book = new Book(2, "La gloire de mon père", "Les deboires de mon père en vélo");
            s.Save(book);
            tx.Commit();
            s.Clear();
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("title", new StopAnalyzer());

            Lucene.Net.Search.Query query = parser.Parse("Summary:noword");
            IQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            IList result = hibQuery.List();
            Assert.AreEqual(0, result.Count);

            query = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
            result = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with explicit class filter");

            query = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query);
            result = hibQuery.List();
            Assert.AreEqual(2, result.Count, "Query with no class filter");
            foreach (Object element in result)
            {
                Assert.IsTrue(NHibernateUtil.IsInitialized(element));
                s.Delete(element);
            }
            s.Flush();
            tx.Commit();

            tx = s.BeginTransaction();
            query = parser.Parse("Summary:Festina Or Brand:Seiko");
            hibQuery = s.CreateFullTextQuery(query);
            result = hibQuery.List();
            Assert.AreEqual(0, result.Count, "Query with delete objects");

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
        public void TestWithQueryParser()
        {
            QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "", new GISAServer.Search.NivelDocumentalSearcher.InstancePerFieldAnalyzerWrapper().instancePerFieldAnalyzerWrapper);
            Query query = qp.Parse("content:\"manobras\"");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits, "!!!! what?");
            
            query = qp.Parse("content:\"porto\"");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits, "!!!! *whew*");

            query = qp.Parse("content:\"manobras porto\"");
            Assert.AreEqual(0, searcher.Search(query, 1).TotalHits, "!!!! *whew*");

            query = qp.Parse("content:\"manobras no porto\"");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits, "!!!! *whew*");
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            BasicConfigurator.Configure();
            //using (var reader = new MsmqLogReader(new Uri("msmq://localhost/test_queue2")))
            //{
            //    reader.Start();

            //    Console.ReadLine();
            //}

            var searcher = new IndexSearcher("messages");
            var parser = new QueryParser("", new StandardAnalyzer());
            //var query = parser.Parse("MessageId:\"b5005080-800c-43c3-a20b-16db773d7663\" AND MessageId:2307015");
            var query = parser.Parse("Timestamp:[\"2008-12-16T08:14:53.9749900\" TO \"2008-12-16T08:14:53.6343650\"]");

            var hits = searcher.Search(query);
            for (int i = 0; i < hits.Length(); i++)
            {
                var doc = hits.Doc(i);
                Console.WriteLine();
                foreach (Fieldable field in doc.GetFields())
                {
                    Console.WriteLine("{0}: {1}", field.Name(), field.StringValue());
                }
                Console.WriteLine();
            }
        }
Ejemplo n.º 8
0
        public static LuceneResult SearchBIMXchange(string field, string key, int pageSize, int pageNumber)
        {
            const string luceneIndexPath = "C:\\LuceneIndex";

            var directory = FSDirectory.Open(new DirectoryInfo(luceneIndexPath));

            var analyzer = new StandardAnalyzer(Version.LUCENE_29);

            var parser = new QueryParser(Version.LUCENE_29, field, analyzer);
            var query = parser.Parse(String.Format("{0}*", key));

            var searcher = new IndexSearcher(directory, true);

            var topDocs = searcher.Search(query, 1000000);

            var docs = new List<Document>();
            var start = (pageNumber-1)*pageSize;
            for (var i = start; i < start + pageSize && i < topDocs.TotalHits; i++)
            {
                var scoreDoc = topDocs.ScoreDocs[i];
                var docId = scoreDoc.doc;
                var doc = searcher.Doc(docId);
                docs.Add(doc);
            }

            searcher.Close();
            directory.Close();
            var result = new LuceneResult {Results = docs, TotalCount = topDocs.TotalHits};
            return result;
        }
Ejemplo n.º 9
0
        public static ICollection<SearchResult> Execute(string query)
        {
            ICollection<SearchResult> searchResults = new List<SearchResult>();

            string directoryPath = AppDomain.CurrentDomain.BaseDirectory + @"\App_Data\LuceneIndexes";
            var directory = FSDirectory.Open(directoryPath);
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);

            var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "SearchBody", analyzer);
            Query searchQuery = parser.Parse(query + "*");

            IndexSearcher searcher = new IndexSearcher(directory);
            TopDocs hits = searcher.Search(searchQuery, 200);
            int results = hits.ScoreDocs.Length;
            for (int i = 0; i < results; i++)
            {
                Document doc = searcher.Doc(hits.ScoreDocs[i].Doc);
                var searchResult = new SearchResult();
                searchResult.EntityId = int.Parse(doc.Get("EntityId"));
                searchResult.EntityTypeName = doc.Get("EntityTypeName");
                searchResult.SearchTitle = doc.Get("SearchTitle");
                searchResult.SearchBody = doc.Get("SearchBody");
                searchResults.Add(searchResult);
            }
            searcher.Dispose();
            directory.Dispose();

            return searchResults;
        }
        public void ResultTransformToDelimString()
        {
            IFullTextSession s = Search.CreateFullTextSession(this.OpenSession());
            this.PrepEmployeeIndex(s);

            s.Clear();
            ITransaction tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("Dept", new StandardAnalyzer());

            Query query = parser.Parse("Dept:ITech");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Employee));
            hibQuery.SetProjection(
                    "Id",
                    "Lastname",
                    "Dept",
                    ProjectionConstants.THIS,
                    ProjectionConstants.SCORE,
                    ProjectionConstants.BOOST,
                    ProjectionConstants.ID);
            hibQuery.SetResultTransformer(new ProjectionToDelimStringResultTransformer());

            IList result = hibQuery.List();
            Assert.IsTrue(((string)result[0]).StartsWith("1000, Griffin, ITech"), "incorrect transformation");
            Assert.IsTrue(((string)result[1]).StartsWith("1002, Jimenez, ITech"), "incorrect transformation");

            // cleanup
            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
Ejemplo n.º 11
0
        public Task<List<TestDocument>> Query(string q)
        {
            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "text", Analyzer);
            Query query = parser.Parse(q);
            IndexSearcher searcher = new IndexSearcher(Index, true);
            //Do the search
            TopDocs docs = searcher.Search(query, 10);

            int results = docs.TotalHits;
            List<TestDocument> ret = new List<TestDocument>();
            for (int i = 0; i < results; i++)
            {
                ScoreDoc d = docs.ScoreDocs[i];
                float score = d.Score;
                Document idoc = searcher.Doc(d.Doc);
                ret.Add(new TestDocument()
                {
                    Id = Convert.ToInt32(idoc.GetField("id").StringValue),
                    Text = idoc.GetField("text").StringValue
                });
            }
            searcher.Dispose();

            return Task.FromResult(ret);
        }
Ejemplo n.º 12
0
        public IEnumerable<Hit> Search(string query, int maxResults)
        {
            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);

            QueryParser qp = new QueryParser(
                Lucene.Net.Util.Version.LUCENE_29,
                "contents",
                analyzer
            );
            Query q = qp.Parse(query);

            TopDocs top = searcher.Search(q, maxResults);
            List<Hit> result = new List<Hit>(top.totalHits);

            for (int index = 0; index < top.totalHits; index++)
            {
                var doc = searcher.Doc(top.scoreDocs[index].doc);
                string contents = doc.Get("contents");

                var scorer = new QueryScorer(q, searcher.GetIndexReader(), "contents");
                var highlighter = new Highlighter(scorer);

                result.Add(new Hit()
                {
                    Relevance = top.scoreDocs[index].score,
                    Title = doc.Get("title"),
                    Url = doc.Get("path"),
                    Excerpt = highlighter.GetBestFragment(analyzer, "contents", contents)
                });
            }

            return result;
        }
Ejemplo n.º 13
0
        public TopDocs SearchIndex(string querytext)
        {
            querytext = querytext.ToLower();
            //  var multiFieldQuery = Parse
            Query   query   = parser.Parse(querytext);
            TopDocs results = searcher.Search(query, 500);

            totalresultLabel.Text = "Total number of result is: " + (results.TotalHits).ToString();
            int i    = 0;
            int rank = 0;

            foreach (ScoreDoc scoreDoc in results.ScoreDocs)
            {
                rank++;
                Array.Resize <string>(ref searchResultList, i + 1);
                Lucene.Net.Documents.Document doc = searcher.Doc(scoreDoc.Doc);
                //string myFieldValue = doc.Get(TEXT_FN).ToString();

                string titleValue    = doc.Get(TITLE_FN).ToString();
                string abstractValue = doc.Get(ABSTRACT_FN).ToString();

                searchResultList[i] = "Q0 " + (scoreDoc.Doc + 1) + " " + rank + " " + scoreDoc.Score + " ";
                i++;
            }

            return(results);
        }
        public List<int> AiComplete(string args)
        {
            List<int> list = new List<int>();

            try
            {
                IndexReader citac = IndexReader.Open(this.folder, true);

                var seracher = new IndexSearcher(citac);

                var queryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Content", new KeywordAnalyzer());

                queryParser.AllowLeadingWildcard = true;

                var query = queryParser.Parse(args+"*");
                TopDocs result = seracher.Search(query, 5);
                var lista = result.ScoreDocs;

                foreach (var hint in lista)
                {

                    var h = seracher.Doc(hint.Doc);

                    list.Add(h.Get("ArticlesID").ToInt());
                }

            }
            catch (Exception)
            {

            }
            return list;
        }
Ejemplo n.º 15
0
        private void button2_Click(object sender, EventArgs e)
        {
            String field = "content";

            IndexReader reader = IndexReader.Open(FSDirectory.Open(new DirectoryInfo(INDEX_DIR.FullName)), true);

            Searcher searcher = new IndexSearcher(reader);
            Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);

            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, field, analyzer);

            Query query = parser.Parse(textBox1.Text.Trim());

            TopScoreDocCollector collector = TopScoreDocCollector.Create(searcher.MaxDoc, false);
            searcher.Search(query, collector);
            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;

            MessageBox.Show(this, "共 " + collector.TotalHits.ToString() + " 条记录");

            //ltrResult.Text = "共 " + collector.GetTotalHits().ToString() + " 条记录<br>";

            //for (Int32 i = 0; i < collector.GetTotalHits(); i++)
            //{
            //    ltrResult.Text += "doc=" + hits[i].doc + " score=" + hits[i].score + "<br>";
            //    Document doc = searcher.Doc(hits[i].doc);
            //    ltrResult.Text += "Path:" + doc.Get("path") + "<br>";
            //}

            reader.Dispose();

        }
Ejemplo n.º 16
0
        public Task<SearchResultCollection> Search(string search)
        {
            return System.Threading.Tasks.Task.Run(() =>
            {
                var src = new SearchResultCollection();
                if (string.IsNullOrWhiteSpace(search)) return src;
                try
                {

                                                       
                    var parser = new QueryParser(Version.LUCENE_30,"All", analyzer);
                    Query q = new TermQuery(new Term("All", search));
                                                           
                    using (var indexSearcher = new IndexSearcher(directory, true))
                    {
                        Query query = parser.Parse(search);
                        TopDocs result = indexSearcher.Search(query, 50);
                        foreach (ScoreDoc h in result.ScoreDocs)
                        {
                            Document doc = indexSearcher.Doc(h.Doc);
                            string id = doc.Get("id");
                            BaseContent value;
                            if (LookupTable.TryGetValue(id, out value)) src.Add(new SearchResult {Relevance = h.Score, Content = value});
                        }
                    }
                }
                catch (Exception e)
                {

                    Logger.Log("DataServer","Error lucene search",e.Message,Logger.Level.Error);
                }
                return src;
            });
        }
Ejemplo n.º 17
0
        public ArrayList getNotesMatchingTitle(string search)
        {
            ArrayList snotes = new ArrayList ();

            try {
                QueryParser parser = new QueryParser ("title", analyzer);

                string lucsearch = search + "*^4" + " content:" + search + "*";

                Query query = parser.Parse (lucsearch);
                IndexSearcher searcher = new IndexSearcher (lucIdx);
                Hits hits = searcher.Search (query);

                int results = hits.Length ();
                Console.WriteLine ("Found {0} results", results);
                for (int i = 0; i < results; i++) {
                    Document doc = hits.Doc (i);
                    //float score = hits.Score (i);
                    snotes.Add (new Note (doc.Get ("title"), doc.Get ("lastmod")));
                }
            } catch (Exception e) {
                Console.WriteLine ("ERROR Search: " + e.Message);
            }

            return snotes;
        }
Ejemplo n.º 18
0
        public void Optimize()
        {
            IFullTextSession s = Search.CreateFullTextSession(OpenSession());
            ITransaction tx = s.BeginTransaction();
            int loop = 2000;
            for (int i = 0; i < loop; i++)
            {
                s.Persist(new Email(i + 1, "JBoss World Berlin", "Meet the guys who wrote the software"));
            }

            tx.Commit();
            s.Close();

            s = Search.CreateFullTextSession(OpenSession());
            tx = s.BeginTransaction();
            s.SearchFactory.Optimize(typeof(Email));
            tx.Commit();
            s.Close();

            // Check non-indexed object get indexed by s.index;
            s = new FullTextSessionImpl(OpenSession());
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("id", new StopAnalyzer());
            int result = s.CreateFullTextQuery(parser.Parse("Body:wrote")).List().Count;
            Assert.AreEqual(2000, result);

            s.Delete("from System.Object");
            tx.Commit();
            s.Close();
        }
Ejemplo n.º 19
0
        public Engine()
        {
            var directory = new RAMDirectory();
            var analyzer = new StandardAnalyzer(Version.LUCENE_30);

            using (var indexWriter = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED))
            {
                for (int i = 0; i < 10000; i++)
                {
                    Console.Write(".");
                    var document = new Document();
                    document.Add(new Field("Id", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    document.Add(new Field("Name", "Name" + i.ToString(), Field.Store.YES, Field.Index.ANALYZED));
                    indexWriter.AddDocument(document);
                }
            }

            Console.ReadKey();

            var queryParser = new QueryParser(Version.LUCENE_30, "Name", analyzer);
            var query = queryParser.Parse("Name37~");

            IndexReader indexReader = IndexReader.Open(directory, true);
            var searcher = new IndexSearcher(indexReader);

            TopDocs resultDocs = searcher.Search(query, indexReader.MaxDoc);
        }
Ejemplo n.º 20
0
        public SearchResult[] Search(string searchString)
        {
            Analyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Version.LUCENE_29);

            QueryParser parser = new QueryParser(Version.LUCENE_29, "Content", analyzer);

            var query = parser.Parse(searchString);

            Searcher searcher = new IndexSearcher(Lucene.Net.Index.IndexReader.Open(directory, true));

            TopScoreDocCollector collector = TopScoreDocCollector.Create(100, true);

            searcher.Search(query, collector);
            var hits = collector.TopDocs().ScoreDocs;

            List<SearchResult> results = new List<SearchResult>();

            for (int i = 0; i < hits.Length; i++)
            {
                int docId = hits[i].Doc;
                float score = hits[i].Score;

                Lucene.Net.Documents.Document doc = searcher.Doc(docId);

                results.Add(new SearchResult
                {
                    BookId = Guid.Parse(doc.Get("BookId")),
                    Score = score
                });
            }

            return results.ToArray();
        }
Ejemplo n.º 21
0
        private void btnExecuteSearch_Click(object sender, EventArgs e)
        {
            Directory indexDirectory = FSDirectory.Open(new System.IO.DirectoryInfo(tempPath));
            IndexSearcher searcher = new IndexSearcher(indexDirectory, true); // read-only=true

            // TODO: QueryParser support for Hebrew terms (most concerning issue is with acronyms - mid-word quotes)
            QueryParser qp = new QueryParser("content", analyzer);
            qp.SetDefaultOperator(QueryParser.Operator.AND);
            Query query = qp.Parse(txbSearchQuery.Text);

            ScoreDoc[] hits = searcher.Search(query, null, 1000).scoreDocs;

            // Iterate through the results:
            BindingList<SearchResult> l = new BindingList<SearchResult>();
            for (int i = 0; i < hits.Length; i++)
            {
                Document hitDoc = searcher.Doc(hits[i].doc);
                SearchResult sr = new SearchResult(hitDoc.GetField("title").StringValue(),
                    hitDoc.GetField("path").StringValue(), hits[i].score);
                l.Add(sr);
            }

            searcher.Close();
            indexDirectory.Close();

            dgvResults.DataSource = l;
        }
        public void HelloWorldTest()
        {
            Directory directory = new RAMDirectory();
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
            IndexWriter writer = new IndexWriter(directory,
                analyzer,
                IndexWriter.MaxFieldLength.UNLIMITED);

            Document doc = new Document();
            doc.Add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
            doc.Add(new Field("postBody", "sample test", Field.Store.YES, Field.Index.ANALYZED));
            writer.AddDocument(doc);
            writer.Optimize();
            writer.Commit();
            writer.Close();

            QueryParser parser = new QueryParser(Version.LUCENE_29, "postBody", analyzer);
            Query query = parser.Parse("sample test");

            //Setup searcher
            IndexSearcher searcher = new IndexSearcher(directory, true);
            //Do the search
            var hits = searcher.Search(query, null, 10);

            for (int i = 0; i < hits.TotalHits; i++)
            {
                var doc1 = hits.ScoreDocs[i];
            }

            searcher.Close();
            directory.Close();
        }
        public ISearchResult Search(string query)
        {
            var timer = new Stopwatch();
            timer.Start();

            var directory = FSDirectory.Open(new DirectoryInfo(path));
            var analyzer = new StandardAnalyzer(Version.LUCENE_29);
            var searcher = new IndexSearcher(directory, true);

            var queryParser = new QueryParser(Version.LUCENE_29, "text", analyzer);
            var result = searcher.Search(queryParser.Parse(query), 20);

            var docs = (from scoreDoc in result.scoreDocs
                        let doc = searcher.Doc(scoreDoc.doc)
                        let fields = new Dictionary<string, string> { { "title", doc.Get("title") }, { "text", doc.Get("text") } }
                        select new LuceneDocument { Id = scoreDoc.doc.ToString(), Fields = fields }).ToList();

            var ret = new SearchResult { Query = query, Total = result.totalHits, Documents = docs, Source = Name };

            searcher.Close();
            directory.Close();

            timer.Stop();
            ret.Duration = (decimal) timer.Elapsed.TotalSeconds;

            return ret;
        }
Ejemplo n.º 24
0
		public void MrsJones()
		{
			var dir = new RAMDirectory();
			var analyzer = new WhitespaceAnalyzer();
			var writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
			var document = new Lucene.Net.Documents.Document();
			document.Add(new Field("Name", "MRS. SHABA", Field.Store.NO, Field.Index.ANALYZED_NO_NORMS));
			writer.AddDocument(document);

			writer.Close(true);

			

			var searcher = new IndexSearcher(dir, true);

			var termEnum = searcher.GetIndexReader().Terms();
			while (termEnum.Next())
			{
				var buffer = termEnum.Term().Text();
				Console.WriteLine(buffer);
			} 

			var queryParser = new QueryParser(Version.LUCENE_29, "", analyzer);
			queryParser.SetLowercaseExpandedTerms(false);
			var query = queryParser.Parse("Name:MRS.*");
			Console.WriteLine(query);
			var result = searcher.Search(query, 10);

			Assert.NotEqual(0,result.totalHits);
		}
Ejemplo n.º 25
0
        public SearchResults Find(string terms)
        {
            Directory directory = FSDirectory.GetDirectory("./index",false);
            // Now search the index:
            var isearcher = new IndexSearcher(directory);
            // Parse a simple query that searches for "text":
            //Query query = QueryParser.Parse("text", "fieldname", analyzer);
            var qp = new QueryParser("description", _analyzer);
            Query query = qp.Parse(terms);

            Hits hits = isearcher.Search(query);

            var sr = new SearchResults();

            // Iterate through the results:
            for (int i = 0; i < hits.Length(); i++)
            {
                Document hitDoc = hits.Doc(i);

                sr.Add(new Result() { Name = hitDoc.Get("name"), Description = hitDoc.Get("description") });
            }
            isearcher.Close();
            directory.Close();

            return sr;
        }
        public void ObjectNotFound()
        {
            ISession sess = OpenSession();
            ITransaction tx = sess.BeginTransaction();

            Author author = new Author();
            author.Name = "Moo Cow";
            sess.Persist(author);

            tx.Commit();
            sess.Clear();
            IDbCommand statement = sess.Connection.CreateCommand();
            statement.CommandText = "DELETE FROM Author";
            statement.ExecuteNonQuery();

            IFullTextSession s = Search.CreateFullTextSession(sess);
            tx = s.BeginTransaction();
            QueryParser parser = new QueryParser("title", new KeywordAnalyzer());
            Lucene.Net.Search.Query query = parser.Parse("name:moo");
            IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Author), typeof(Music));
            IList result = hibQuery.List();
            Assert.AreEqual(0, result.Count, "Should have returned no author");

            foreach (object o in result)
            {
                s.Delete(o);
            }

            tx.Commit();
            s.Close();
        }
Ejemplo n.º 27
0
        public TextSearchResult Search(string query, Tenant tenant)
        {
            var result = new TextSearchResult(module);

            if (string.IsNullOrEmpty(query) || !Directory.Exists(path))
            {
                return result;
            }

            var dir = Lucene.Net.Store.FSDirectory.Open(new DirectoryInfo(path));
            var searcher = new IndexSearcher(dir, false);
            try
            {
                var analyzer = new AnalyzersProvider().GetAnalyzer(tenant.GetCulture().TwoLetterISOLanguageName);
                var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Text", analyzer);
                parser.SetDefaultOperator(QueryParser.Operator.AND);
                if (TextIndexCfg.MaxQueryLength < query.Length)
                {
                    query = query.Substring(0, TextIndexCfg.MaxQueryLength);
                }
                Query q = null;
                try
                {
                    q = parser.Parse(query);
                }
                catch (Lucene.Net.QueryParsers.ParseException) { }
                if (q == null)
                {
                    q = parser.Parse(QueryParser.Escape(query));
                }

#pragma warning disable 618
                var hits = searcher.Search(q);
#pragma warning restore 618
                for (int i = 0; i < hits.Length(); i++)
                {
                    var doc = hits.Doc(i);
                    result.AddIdentifier(doc.Get("Id"));
                }
            }
            finally
            {
                searcher.Close();
                dir.Close();
            }
            return result;
        }
Ejemplo n.º 28
0
        public static void Arquive(string text, string url, bool isEnglish)
        {
            //INICIALIZAR VARIÁVEIS CONSOANTE SER EM INGLÊS OU EM PORTUGUÊS
            string directory;
            Lucene.Net.Analysis.Analyzer analyzer;
            Object _mon= isEnglish? _monEn : _monPt;
            InitPathAndAnalyzer(out directory, out analyzer, isEnglish);

            //CRIAR UM NOVO DOCUMENTO COM A INFORMAÇÃO NECESSÁRIA: UM CAMPO COM O URL E UM OUTRO COM O CONTEUDO A ANALIZAR
            string hash= text.GetHashCode().ToString();
            Document document = new Document();
            document.Add(new Field("url", url, Field.Store.YES,Field.Index.NOT_ANALYZED));
            document.Add(new Field("text", text, Field.Store.NO, Field.Index.ANALYZED));
            document.Add(new Field("hash",hash, Field.Store.YES, Field.Index.NOT_ANALYZED));

            Monitor.Enter(_mon);
            Lucene.Net.Store.Directory dir = Lucene.Net.Store.FSDirectory.Open(new DirectoryInfo(directory));
            if (System.IO.Directory.GetFiles(directory).Length == 0)
            {
                IndexWriter init = new IndexWriter(dir, analyzer, true, new IndexWriter.MaxFieldLength(25000));
                init.Dispose();
            }

            //VERIFICAR SE O DOCUMENTO JÁ EXISTE E SE CONTEM A MESMA INFORMAÇÃO QUE JÁ LÁ SE ENCONTRA

            IndexSearcher isearcher = new IndexSearcher(dir, false);
            //O CAMPO DE PROCURA SERA O URL
            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "url", analyzer);
            Query query = parser.Parse(url);
            int s = isearcher.IndexReader.NumDocs();
            //Console.WriteLine(isearcher.IndexReader.NumDocs());

            ScoreDoc[] hits = isearcher.Search(query, null, 1000).ScoreDocs;
            if(hits.Length>0){
                 Document doc = isearcher.Doc(hits[0].Doc);

                 //Console.WriteLine(doc.Get("url"));

                //É IGUAL
                 if (doc.Get("hash").Equals(hash))
                 {
                     Monitor.Exit(_mon);
                     return;
                 }
                 //É DIFERENTE
                 else
                 {
                     isearcher.IndexReader.DeleteDocument(hits[0].Doc);

                 }
            }
            isearcher.Dispose();
            //ACEDER AO INDEX COM A INFORMAÇÃO INDEXADA DA LINGUAGEM CORRECTA E ADICIONAR O NOVO DOCUMENTO
            IndexWriter iwriter = new IndexWriter(dir, analyzer, false, new IndexWriter.MaxFieldLength(25000));
            iwriter.AddDocument(document);
            iwriter.Optimize();
            iwriter.Dispose();
            Monitor.Exit(_mon);
        }
Ejemplo n.º 29
0
        public void TestTerms2() // "Olá", "Rosa"
        {
            QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "", customdAnalyzer);
            Query query = qp.Parse("term:Olá");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits);

            query = qp.Parse("term:olá");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits);

            query = qp.Parse("term:Ola");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits);

            query = qp.Parse("term:ola");
            Assert.AreEqual(1, searcher.Search(query, 1).TotalHits);

            // o standart analyzer retorna resultados independentemente de os termos terem ou não maiúsculas
        }
Ejemplo n.º 30
0
 public static Query Raw(this BooleanQuery booleanQuery, string field, string queryText, BooleanClause.Occur occur = null)
 {
     Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
     QueryParser queryParser = new QueryParser(Version.LUCENE_29, field, analyzer);
     Query query = queryParser.Parse(queryText);
     booleanQuery.Add(query, occur);
     return query;
 }
Ejemplo n.º 31
0
        public Query CreateFullPhrase(string searchText)
        {
            Query parsedSearch;

            try
            {
                string output = "\"";
                output      += searchText.Replace("\"", "").ToLower();
                output      += "\"";
                parsedSearch = parser.Parse(output);
            }
            catch
            {
                parsedSearch = null;
            }
            return(parsedSearch);
        }
Ejemplo n.º 32
0
 private Query Parse(QueryParser parser, string value)
 {
     if (string.IsNullOrEmpty(value))
     {
         throw new InvalidOperationException("The key value for field " + parser.Field + " must not be blank.");
     }
     return parser.Parse(QueryParser.Escape(value));
 }
Ejemplo n.º 33
0
        public void TestTerms1() // "[Rosa]", "Rosa"
        {
            QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "", customdAnalyzer);
            Query query = qp.Parse("term:\"Rosa\"");
            Assert.AreEqual(2, searcher.Search(query, 2).TotalHits);

            query = qp.Parse("term:\"\\[Rosa\\]\"");
            Assert.AreEqual(2, searcher.Search(query, 2).TotalHits);

            query = qp.Parse("term:Rosa");
            Assert.AreEqual(2, searcher.Search(query, 2).TotalHits);

            // usando o standard analyzer os '[' ']' são suprimidos daí os 2 documentos serem sempre retornados em qualquer uma das situações

            //query = qp.Parse("term:[Rosa]");
            //hits = searcher.Search(query);
            //Assert.AreEqual(1, hits.Length());
        }
Ejemplo n.º 34
0
        public TopDocs SearchIndex(string querytext)
        {
            querytext = querytext.ToLower();
            Query   query   = parser.Parse(querytext);
            TopDocs results = searcher.Search(query, 2800);

            NoOfDocs = results.TotalHits;
            return(results);
        }
Ejemplo n.º 35
0
        public TopDocs SearchIndex(string queryStr)
        {
            Console.WriteLine($"Searching for: {queryStr}");
            Query   query   = parser.Parse(queryStr);
            TopDocs results = searcher.Search(query, 100);

            Console.WriteLine($"Number of results is {results.TotalHits}");
            return(results);
        }
        public TopDocs SearchIndex(string term)
        {
            Query       query       = parser.Parse(term);
            PhraseQuery phraseQuery = parser.PhraseSlop(term);

            Lucene.Net.Search.TopDocs topDocs = searcher.Search(query, 10);
            Console.WriteLine(topDocs.TotalHits + " documents has been returned.");
            return(topDocs);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Searches the index with the specified query text
        /// </summary>
        /// <param name="querytext">Text to search the index</param>
        /// <returns></returns>
        public TopDocs SearchIndex(string querytext)
        {
            System.Console.WriteLine("Searching for " + querytext);
            querytext = querytext.ToLower();
            Query   query   = parser.Parse(querytext);
            TopDocs results = searcher.Search(query, 10);

            System.Console.WriteLine("Found " + results.TotalHits + " documents.");
            return(results);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Searches the index with the specified query text
        /// </summary>
        /// <param name="querytext">Text to search the index</param>
        /// <returns></returns>
        public TopDocs SearchIndex(string querytext)
        {
            //form.ResultsUpdate("Searching for " + querytext);
            querytext = querytext.ToLower();
            Query   query   = parser.Parse(querytext);
            TopDocs results = searcher.Search(query, 10);

            //form.ResultsUpdate("Found " + results.TotalHits + " documents.");
            return(results);
        }
Ejemplo n.º 39
0
        public Lucene.Net.Search.TopDocs SearchIndex(string text)
        {
            Console.WriteLine("Searching for " + text);
            text.ToLower();
            Query query = parser.Parse(text);

            Lucene.Net.Search.TopDocs doc = searcher.Search(query, 3);

            Console.WriteLine("Total no of Results " + doc.TotalHits.ToString());
            return(doc);
        }
Ejemplo n.º 40
0
        /// Executes the query.
        //  Preprocesses the query text entered by the user
        //  and queries the index.
        //  Calculates the total time to run the query
        //  and sets some text variables for later use.
        public int RunQuery(string text, bool preproc, out string qText)
        {
            // start timer...
            DateTime start = DateTime.Now;

            // get the query settings from the collection
            IRQueryParams queryParams = myCollection.GetQueryParams();

            string[] queryFields      = queryParams.Fields;
            float[]  queryFieldBoosts = queryParams.FieldBoosts;

            // build field boost dictionary
            IDictionary <string, float> boosts = new Dictionary <string, float>();

            for (int i = 0; i < queryFields.Length; i++)
            {
                boosts.Add(queryFields[i], queryFieldBoosts[i]);
            }

            // setup searcher, query and parser
            CreateSearcher();
            Query query;

            parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30,
                                               queryFields, analyzer, boosts);

            // preprocess query (if required)
            if (preproc == true)
            {
                query = PreprocessQuery(text, parser);
            }
            else
            {
                // no preprocessing
                query = parser.Parse(text);
            }

            // print query text to form
            qText = query.ToString();

            // execute the search
            searchResults = searcher.Search(query, maxResults);

            // end timer and calculate total time
            DateTime end      = DateTime.Now;
            TimeSpan duration = end - start;

            queryTime = duration.Seconds + (float)duration.Milliseconds / 1000;

            CleanUpSearcher();

            return(searchResults.TotalHits);
        }
        public TopDocs SearchIndex(string query)
        {
            Console.WriteLine($"Searching for {query}...");
            // construct a lucene query
            Query qo = parser.Parse(query);

            // retrieve the results using the query
            TopDocs td = searcher.Search(qo, 100);

            // return the results
            return(td);
        }
Ejemplo n.º 42
0
        public static List <Models.SearchResult> Query(string text, int max = 8, string userId = null)
        {
            if (!string.IsNullOrEmpty(text) && !text.EndsWith(":"))
            {
                userId = string.IsNullOrEmpty(userId) ? Account.AuditId : userId;
                var analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);         //todo: what version?
                var parser   = new Lucene.Net.QueryParsers.QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", analyzer); //text is just the default field to search
                var query    = parser.Parse(text);
                //var term = new Term("text", text.ToLower());
                //var query = new Lucene.Net.Search.PrefixQuery(term); //parser.Parse(text);
                //var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "text", analyzer).Parse(text.ToLower());

                using (var dir = FSDirectory.Open(new DirectoryInfo(IndexDir)))
                {
                    using (var searcher = new IndexSearcher(dir, true))
                    {
                        var collector = TopScoreDocCollector.create(max * 2, true); //todo: mini-hack to accomidate the post-filtering of search results - attempt to get twice as many results as we need.  hopefully we won't filter out that many...
                        searcher.Search(query, collector);
                        var hits = collector.TopDocs().ScoreDocs;

                        //var hits = searcher.Search(query);
                        var ret = new List <Models.SearchResult>();

                        for (var i = 0; i < hits.Length; i++)
                        {
                            var docId    = hits[i].doc;
                            var doc      = new Models.SearchDocument(searcher.Doc(docId));
                            var provider = GetDocumentProvider(doc.Type);
                            if (provider != null)
                            {
                                if (provider.IsAuthorized(doc, userId))
                                {
                                    ret.Add(provider.FormatResult(doc));
                                }
                            }
                            else
                            {
                                throw new Exception(string.Format("Formatter for type {0} not found", doc.Type));
                            }

                            if (ret.Count >= max)   //todo: mini-hack to accomidate the post-filtering of search results
                            {
                                break;
                            }
                        }

                        return(ret);
                    }
                }
            }
            return(new List <SearchResult>());
        }
Ejemplo n.º 43
0
        //search
        public string SearchIndex(string queryText)
        {
            string output = "Nothing";

            if (queryText != "")
            {
                queryText.ToLower();
                Query query = parser.Parse(queryText);
                docs = searcher.Search(query, 1400);//here, 1400 means requiring to find up to 1400 documents
                //because it is impossible to be more than 1400.

                numofrelevant = docs.TotalHits;                                                       //it represent how many documents found already(no more than 100)
                output        = "There are " + numofrelevant.ToString() + " relavant documents.\r\n"; //display

                numofdoc = 10;
                int totaldoc = 10;
                if (docs.ScoreDocs.Length < 10)
                {
                    totaldoc = docs.ScoreDocs.Length;
                }
                if (numofrelevant > 0)
                {
                    output = output + "The relevant documents from 1 to " + totaldoc.ToString() + " are as follow:\r\n";
                }
                option.Clear();//option is a list used to store the documents found in the screen.notice, if the screen is changed, the option list will be changed.
                for (int i = 0; i < totaldoc; i++)
                {
                    ScoreDoc scoredoc = docs.ScoreDocs[i];
                    Document doc1     = searcher.Doc(scoredoc.Doc);
                    option.Add(doc1.Get(DocID));
                    //output = output + "Document " + scoredoc.Doc.ToString() + ":\r\n";
                    output = output + "Rank " + (i + 1).ToString() + ": " + DocID + ":" + doc1.Get(DocID) + "\r\n";
                    output = output + TITLE + ":" + doc1.Get(TITLE) + "\r\n";
                    output = output + AUTHOR + ":" + doc1.Get(AUTHOR) + "\r\n";
                    output = output + BIBLiINFO + ":" + doc1.Get(BIBLiINFO) + "\r\n";
                    //because requirement is to show the first sentence.
                    char[]   symbols   = { '.', '?', '!' };
                    string[] sentences = doc1.Get(ABSTRACT).ToString().Split(symbols, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string sentence in sentences)
                    {
                        if (sentence.Length > 0)
                        {
                            output = output + "The first sentence of teh abstract:" + sentence + "\r\n";
                            break;//once I find the first sentence, I will jump out of the loop.
                        }
                    }
                    //output = output + "The score is" + scoredoc.Score.ToString()+"\r\n";
                }
            }
            return(output);
        }//end index search
Ejemplo n.º 44
0
 public void RunSearch()
 {
     BeginRunSearch();
     try
     {
         LuceneQueryParsers.QueryParser parser = CreateQueryParser();
         LuceneSearch.Query             q      = parser.Parse(IndexQueryDefinition.QueryText);
         QueryHits = IndexSearcher.Search(q, IndexQueryDefinition.TopDocsToFind);
     }
     finally
     {
         EndRunSearch();
     }
 }
Ejemplo n.º 45
0
        /***
         * Understands the lucene query syntax
         */
        public List <Utilities.Language.TextIndexing.IndexResult> GetDocumentsWithQuery(string query)
        {
            List <Utilities.Language.TextIndexing.IndexResult> fingerprints = new List <Utilities.Language.TextIndexing.IndexResult>();
            HashSet <string> fingerprints_already_seen = new HashSet <string>();

            try
            {
                using (Lucene.Net.Index.IndexReader index_reader = Lucene.Net.Index.IndexReader.Open(LIBRARY_INDEX_BASE_PATH, true))
                {
                    using (Lucene.Net.Search.IndexSearcher index_searcher = new Lucene.Net.Search.IndexSearcher(index_reader))
                    {
                        Lucene.Net.QueryParsers.QueryParser query_parser = new Lucene.Net.QueryParsers.QueryParser(Version.LUCENE_29, "content", analyzer);

                        Lucene.Net.Search.Query query_object = query_parser.Parse(query);
                        Lucene.Net.Search.Hits  hits         = index_searcher.Search(query_object);

                        var i = hits.Iterator();
                        while (i.MoveNext())
                        {
                            Lucene.Net.Search.Hit hit = (Lucene.Net.Search.Hit)i.Current;
                            string fingerprint        = hit.Get("fingerprint");
                            string page = hit.Get("page");

                            if (!fingerprints_already_seen.Contains(fingerprint))
                            {
                                fingerprints_already_seen.Add(fingerprint);

                                IndexResult index_result = new IndexResult {
                                    fingerprint = fingerprint, score = hit.GetScore()
                                };
                                fingerprints.Add(index_result);
                            }
                        }

                        // Close the index
                        index_searcher.Close();
                    }
                    index_reader.Close();
                }
            }
            catch (Exception ex)
            {
                Logging.Warn(ex, "GetDocumentsWithQuery: There was a problem opening the index file for searching.");
            }

            return(fingerprints);
        }
Ejemplo n.º 46
0
        public TopDocs SearchForQuery(string querytext, out Lucene.Net.Search.Query query, bool toProcess) // Searches index with query text
        {
            Stopwatch stopwatch2 = Stopwatch.StartNew();

            querytext = querytext.ToLower();
            if (!toProcess)
            {
                querytext = "\"" + querytext + "\"";
            }
            query = parser.Parse(querytext);
            stopwatch2.Stop();
            queryTime  = stopwatch2.Elapsed.TotalSeconds.ToString();
            finalQuery = query.ToString();
            TopDocs results = searcher.Search(query, 100);

            return(results);
        }
        // Processes query and ranks results
        public void SearchIndex(string querytext, ref TopDocs results, ref int numberOfDocuments)
        {
            parser    = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, TEXT_FN, analyzer);
            querytext = querytext.ToLower();
            Query query = parser.Parse(querytext);

            results           = searcher.Search(query, 1400);
            numberOfDocuments = results.TotalHits;
            int rank = 0;

            foreach (ScoreDoc scoreDoc in results.ScoreDocs)
            {
                rank++;
                // retrieve the document from the 'ScoreDoc' object
                Lucene.Net.Documents.Document doc = searcher.Doc(scoreDoc.Doc);
                string myFieldValue = doc.Get(TEXT_FN).ToString();
                //Console.WriteLine("Rank " + rank + " text " + myFieldValue);
            }
        }
Ejemplo n.º 48
0
        static void SearchForPhrase(IndexSearcher searcher, string phrase)
        {
            using (new AutoStopWatch(string.Format("Search for {0}", phrase)))
            {
                Lucene.Net.QueryParsers.QueryParser parser = new Lucene.Net.QueryParsers.QueryParser("Body", new StandardAnalyzer());
                Lucene.Net.Search.Query             query  = parser.Parse(phrase);

                Hits hits = searcher.Search(query);
                Console.WriteLine("Found {0} results for {1}", hits.Length(), phrase);
                int max = hits.Length();
                if (max > 100)
                {
                    max = 100;
                }
                for (int i = 0; i < max; i++)
                {
                    Console.WriteLine(hits.Doc(i).GetField("Title").StringValue());
                }
            }
        }
Ejemplo n.º 49
0
        static void SearchForPhrase(IndexSearcher searcher, string phrase)
        {
            using (new AutoStopWatch(string.Format("Search for {0}", phrase)))
            {
                Lucene.Net.QueryParsers.QueryParser parser = new Lucene.Net.QueryParsers.QueryParser(Lucene.Net.Util.Version.LUCENE_CURRENT, "Body", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_CURRENT));
                Lucene.Net.Search.Query             query  = parser.Parse(phrase);

                var hits = searcher.Search(query, 100);
                Console.WriteLine("Found {0} results for {1}", hits.TotalHits, phrase);
                int max = hits.TotalHits;
                if (max > 100)
                {
                    max = 100;
                }
                for (int i = 0; i < max; i++)
                {
                    Console.WriteLine(hits.ScoreDocs[i].Doc);
                }
            }
        }
Ejemplo n.º 50
0
        public TopDocs SearchIndex(string querytext)
        {
            System.Console.WriteLine("Searching for " + querytext);
            querytext = querytext.ToLower();
            Query   query   = parser.Parse(querytext);
            TopDocs results = searcher.Search(query, 500);

            totalresultLabel.Text = "Total number of result is " + (results.TotalHits).ToString();

            int rank = 0;

            foreach (ScoreDoc scoreDoc in results.ScoreDocs)
            {
                rank++;
                Lucene.Net.Documents.Document doc = searcher.Doc(scoreDoc.Doc);
                string myFieldValue = doc.Get(TEXT_FN).ToString();
            }

            return(results);
        }
Ejemplo n.º 51
0
        public SearchModel Search(string searchText)
        {
            var result = new SearchModel();

            if (string.IsNullOrEmpty(searchText))
            {
                result.Message = "Įveskite paieškos užklausą.";
                return(result);
            }

            var stemmedSearchText = new LithuanianStemmer().Stem(searchText.Trim());

            if (string.IsNullOrEmpty(stemmedSearchText))
            {
                result.Message = "Įveskite paieškos užklausą.";
                return(result);
            }

            Lucene.Net.Search.Hits hits = null;
            try
            {
                if (char.IsLetter(stemmedSearchText[stemmedSearchText.Length - 1]))
                {
                    stemmedSearchText += "*";
                }

                query = parser.Parse(stemmedSearchText);

                if (searcher == null)
                {
                    searcher = new Lucene.Net.Search.IndexSearcher(CustomAppSettings.SearchIndexFolder);
                }

                hits = searcher.Search(query);
            }
            catch (Exception e)
            {
                result.Message = "Paieška nepavyko. Pataisykite užklausą. Klaidos pranešimas: " + e.Message;
                return(result);
            }

            Lucene.Net.Highlight.Formatter formatter = new Lucene.Net.Highlight.SimpleHTMLFormatter(
                "<span class=\"highlightResult\">",
                "</span>");

            var fragmenter  = new Lucene.Net.Highlight.SimpleFragmenter(100);
            var scorer      = new Lucene.Net.Highlight.QueryScorer(searcher.Rewrite(query));
            var highlighter = new Lucene.Net.Highlight.Highlighter(formatter, scorer);

            highlighter.SetTextFragmenter(fragmenter);

            Dictionary <string, int> dict_already_seen_ids = new Dictionary <string, int>();

            var list = new List <SearchIndexModel>();

            // insert the search results into a temp table which we will join with what's in the database
            for (int i = 0; i < hits.Length(); i++)
            {
                if (dict_already_seen_ids.Count < 100)
                {
                    Lucene.Net.Documents.Document doc = hits.Doc(i);
                    string id = doc.Get("id");
                    if (!dict_already_seen_ids.ContainsKey(id))
                    {
                        dict_already_seen_ids[id] = 1;
                        var model = new SearchIndexModel();
                        model.Id      = id;
                        model.Score   = hits.Score(i);
                        model.Subject = doc.Get("subject");
                        model.Type    = (EntryTypes)Enum.Parse(typeof(EntryTypes), doc.Get("type"));

                        string raw_text = HttpUtility.HtmlEncode(doc.Get("raw_text"));
                        //string raw_text = doc.Get("raw_text");

                        Lucene.Net.Analysis.TokenStream stream = analyzer.TokenStream("text",
                                                                                      new System.IO.StringReader(
                                                                                          raw_text));
                        string highlighted_text = highlighter.GetBestFragments(stream, raw_text, 3, "...").Replace("'",
                                                                                                                   "''");


                        if (highlighted_text == "") // someties the highlighter fails to emit text...
                        {
                            highlighted_text = raw_text.Replace("'", "''");
                        }
                        if (highlighted_text.Length > 3000)
                        {
                            highlighted_text = highlighted_text.Substring(0, 3000);
                        }

                        model.HighlightedText = highlighted_text;

                        list.Add(model);
                    }
                }
                else
                {
                    break;
                }
            }

            result.List         = list;
            result.SearchPhrase = searchText;
            if (list.Count == 0)
            {
                result.Message = string.Format("Įrašų pagal užklausą '{0}' nerasta. Patikslinkite paieškos duomenis.", searchText);
            }

            return(result);
        }