Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Ejemplo n.º 1
0
        protected virtual void Dispose(bool disposing)
        {
            lock (padlock)
            {
                if (disposed == false)
                {
                    SerializeItemsToIndex();

                    if (disposing)
                    {
                        if (indexSearcher != null)
                        {
                            indexSearcher.Dispose();
                        }
                        if (IndexWriter != null)
                        {
                            IndexWriter.Dispose();
                        }
                        if (IndexDirectory != null)
                        {
                            IndexDirectory.Dispose();
                        }
                    }

                    // Indicate that the instance has been disposed.
                    IndexWriter    = null;
                    indexSearcher  = null;
                    IndexDirectory = null;
                    disposed       = true;
                }
            }
        }
Ejemplo n.º 2
0
        public Data searchLucene(Data data)
        {
            Account_lg account = new Account_lg();
            List<string> item = new List<string>();
            Lucene.Net.Store.Directory directory = FSDirectory.Open(new DirectoryInfo("C:\\Visual Studio 2010\\Transaction" + "\\LuceneIndex"));
            var analyzer = new StandardAnalyzer(Version.LUCENE_29);
            IndexReader reader = IndexReader.Open(directory, true);
            IndexSearcher searcher = new IndexSearcher(reader);

            MultiFieldQueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, new string[] { "name", "username" }, analyzer);  //search for multifield
            Query query = parser.Parse((data.getString("search")) + "*"); //cant search blank text with wildcard as first character

            TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);
            searcher.Search(query, collector);
            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;
            int count = hits.Length;

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

                Document doc = searcher.Doc(docId);

                string id = doc.Get("id");
                item.Add(id);
            }
            Data list = account.selectUser(data, item.ToArray());
            reader.Dispose();
            searcher.Dispose();

            return list;
        }
    static void Main(string[] args)
    {
        // Directory where index is saved.
        Directory indexDirectory = FSDirectory.Open(@"C:\Users\pvlachos\Desktop\index");

        // Initializing Lucene.
        Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);

        // Creating IndexReader instance to read the index file.
        IndexReader reader = IndexReader.Open(indexDirectory, false);

        Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(reader);

        int totalDocuments = reader.NumDocs();                                                         // returns the total number of documents in the index directory

        QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "mainText", analyzer); // where "mainText", is the field(s) I hit with queries
        string      searchTerm;

        Console.WriteLine("You have indexed {0} files in your index folder.", totalDocuments);
        Console.WriteLine("\n");
        Highlighter();
        Console.WriteLine("\n");
        Console.WriteLine("Enter the search term:");
        Console.Write(">");
        while ((searchTerm = Console.ReadLine()) != String.Empty)
        {
            Search(searchTerm, searcher, parser, indexDirectory, totalDocuments);
            Console.Write(">");
        }
        searcher.Dispose();
        reader.Dispose();
        indexDirectory.Dispose();
    }
        private static IEnumerable<CustomerId> _search(string searchQuery)
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<CustomerId>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(_directory, false))
            {
                var hits_limit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_29);

                {
                    //var query = new TermQuery(new Term("CustomerName", searchQuery));
                    var query = new BooleanQuery();
                    query.Add(new TermQuery(new Term("CustomerName", searchQuery)), Occur.MUST);
                    var hits = searcher.Search(query, hits_limit).ScoreDocs;
                    var results = _mapLuceneToDataList(hits, searcher);

                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
                
            }
        }
		// main search method
		private static IEnumerable<SampleData> _search(string searchQuery, string searchField = "") {
			// validation
			if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<SampleData>();

			// set up lucene searcher
			using (var searcher = new IndexSearcher(_directory, false)) {
				var hits_limit = 1000;
				var analyzer = new StandardAnalyzer(Version.LUCENE_29);

				// search by single field
				if (!string.IsNullOrEmpty(searchField)) {
					var parser = new QueryParser(Version.LUCENE_29, searchField, analyzer);
					var query = parseQuery(searchQuery, parser);
					var hits = searcher.Search(query, hits_limit).ScoreDocs;
					var results = _mapLuceneToDataList(hits, searcher);
					analyzer.Close();
					searcher.Close();
					searcher.Dispose();
					return results;
				}
				// search by multiple fields (ordered by RELEVANCE)
				else {
					var parser = new MultiFieldQueryParser
						(Version.LUCENE_29, new[] {"Id", "Name", "Description"}, analyzer);
					var query = parseQuery(searchQuery, parser);
					var hits = searcher.Search(query, null, hits_limit, Sort.INDEXORDER).ScoreDocs;
					var results = _mapLuceneToDataList(hits, searcher);
					analyzer.Close();
					searcher.Close();
					searcher.Dispose();
					return results;
				}
			}
		}
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
0
 public Lucene.Net.Search.TopDocs SearchIndex(string text)
 {
     text.ToLower();
     query = parser.Parse(text);
     Lucene.Net.Search.TopDocs doc = searcher.Search(query, 1000);
     searcher.Dispose();
     return(doc);
 }
Ejemplo n.º 8
0
        private void StartSearch()
        {
            string searchText = txtSearch.Text;
            string whitelist  = "^[a-zA-Z0-9-,. ]+$";
            Regex  pattern    = new Regex(whitelist);

            if (!pattern.IsMatch(searchText))
            {
                throw new Exception("Invalid Search Criteria");
            }

            //Supply conditions
            Analyzer    analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
            QueryParser parser   = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Contents", analyzer);

            Query query = parser.Parse(searchText);

            string indexPath = HttpContext.Current.Request.PhysicalPath.Replace("Default.aspx", "Indexes\\");

            Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(indexPath));

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

            TopDocs topDocs = searcher.Search(query, 100);

            int countResults = topDocs.ScoreDocs.Length;

            if (lblSearchResults.Text.Length > 0)
            {
                lblSearchResults.Text = "";
            }

            if (countResults > 0)
            {
                string results;

                results = string.Format("<br />Search Results <br />");
                for (int i = 0; i < countResults; i++)
                {
                    ScoreDoc scoreDoc = topDocs.ScoreDocs[i];
                    int      docId    = scoreDoc.Doc;
                    float    score    = scoreDoc.Score;

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

                    string docPath = doc.Get("FileName");
                    string urlLink = "~/" + docPath.Substring(docPath.LastIndexOf("Help"), docPath.Length - docPath.LastIndexOf("Help")).Replace("\\", "/");
                    results += "Text found in: <a href=" + urlLink.Replace("~/Help/", "") + "?txtSearch=" + searchText + ">" + urlLink + "</a><br />";
                }
                lblSearchResults.Text += results;
            }
            else
            {
                lblSearchResults.Text = "No records found for \"" + searchText + "\"";
            }

            searcher.Dispose();
        }
Ejemplo n.º 9
0
        public List <Item> search(string keyWord)
        {
            //string strAnalyzerType = comboBox2.SelectedItem.ToString();
            string strAnalyzerType = "StandardAnalyzer";

            if (comboBox2.SelectedItem != null)
            {
                strAnalyzerType = comboBox2.SelectedItem.ToString();
            }
            string strType = "A";

            if (textBox3.Text != "")
            {
                strType = textBox3.Text.ToString();
            }
            FSDirectory dir     = FSDirectory.Open(indexLocation);
            List <Item> results = new List <Item>();

            Lucene.Net.Util.Version      AppLuceneVersion = Lucene.Net.Util.Version.LUCENE_30;
            Lucene.Net.Analysis.Analyzer analyzer         = AnalyzerHelper.GetAnalyzerByName(strAnalyzerType);
            //Lucene.Net.QueryParsers.MultiFieldQueryParser parser = new Lucene.Net.QueryParsers.MultiFieldQueryParser(AppLuceneVersion,new string[] { "content","title" }, analyzer);
            IDictionary <String, Single> dictionary = new Dictionary <String, Single>();

            dictionary.Add("title", 5);
            dictionary.Add("content", 10);
            Lucene.Net.QueryParsers.MultiFieldQueryParser parser = new Lucene.Net.QueryParsers.MultiFieldQueryParser(AppLuceneVersion, new string[] { "title", "content" }, analyzer);
            //parser.DefaultOperator = Lucene.Net.QueryParsers.QueryParser.Operator.AND;
            Lucene.Net.Search.Query query = parser.Parse(keyWord);
            //parser.
            //BooleanClause
            //Lucene.Net.Search.BooleanClause booleanClauses = new BooleanClause();
            //BooleanClause
            //    BooleanClause.Occur[] flags = new BooleanClause.Occur[] { BooleanClause.Occur.MUST, BooleanClause.Occur.MUST };
            Occur[] occurs = new Occur[] { Occur.MUST, Occur.MUST };
            Lucene.Net.Search.Query query2 = Lucene.Net.QueryParsers.MultiFieldQueryParser.Parse(AppLuceneVersion, new string[] { keyWord, strType }, new string[] { "content", "title" }, occurs, analyzer);

            Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
            TopDocs topdocs = searcher.Search(query2, 100);

            Lucene.Net.Search.ScoreDoc[] hits = topdocs.ScoreDocs;

            foreach (var hit in hits)
            {
                var foundDoc = searcher.Doc(hit.Doc);
                results.Add(new Item {
                    title = foundDoc.Get("title"), content = foundDoc.Get("content")
                });
            }
            searcher.Dispose();
            return(results);
        }
Ejemplo n.º 10
0
        private static IEnumerable<LuceneSearchEO> _search(LuceneSearchType searchType, string searchQuery, string searchField = "")
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<LuceneSearchEO>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(getFSDirectory(searchType), false))
            {
                var hits_limit = 20;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                // search by single field
                if (!string.IsNullOrEmpty(searchField))
                {
                    var parser = new QueryParser(Version.LUCENE_30, searchField, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    var hits = searcher.Search(query, hits_limit).ScoreDocs;
                    var results = _mapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
                // search by multiple fields (ordered by RELEVANCE)
                else
                {
                    string[] fields = getLuceneSearchEOFields();
                    var parser = new MultiFieldQueryParser
                        (Version.LUCENE_30, fields, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    var hits = searcher.Search(query, null, hits_limit, Sort.INDEXORDER).ScoreDocs;
                    var results = _mapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
            }
        }
Ejemplo n.º 11
0
 public static List<string> SearchLucene(string searchQuery)
 {
     var directory = FSDirectory.Open(new DirectoryInfo("C:\\rm_index"));
     using (var searcher = new IndexSearcher(directory, false))
     {
         var analyzer = new StandardAnalyzer(Version.LUCENE_30);
         var parser = new QueryParser(Version.LUCENE_30, "DIRECCION_FINAL", analyzer);
         var query = ParseQuery(searchQuery, parser);
         var hits = searcher.Search(query, hits_limit).ScoreDocs;
         var results = hits.Select(hit => MapLuceneDocumentToData(searcher.Doc(hit.Doc))).ToList();
         analyzer.Close();
         searcher.Dispose();
         return results;
     }
 }
Ejemplo n.º 12
0
        public static List<Post> getClanciByTag(int TAGID)
        {
            Directory directoryPronadjeniClanciTagovi = Data.Lucene.Indexing.GetDirectoryClanciTagovi();
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
            IndexReader indexReader = IndexReader.Open(directoryPronadjeniClanciTagovi, true);
            Searcher searcher = new IndexSearcher(indexReader);

            //var queryParser = new QueryParser(Version.LUCENE_30, "Naslov", analyzer);
            var queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { "PostID", "TagID", "DatumKreiranja" }, analyzer);
            var query = queryParser.Parse(Convert.ToString(TAGID)); // Rastavljanje rečenice na rijeci

            TopDocs pronadjeno = searcher.Search(query, indexReader.MaxDoc);
            List<Post> postovi = new List<Post>();

            if (pronadjeno != null)
            {
                var hits = pronadjeno.ScoreDocs;
                foreach (var hit in hits)
                {
                    var documentFromSearcher = searcher.Doc(hit.Doc);
                    using (TriglavBL temp = new TriglavBL())
                    {
                        postovi.Add(temp.getPostByID(Convert.ToInt32(documentFromSearcher.Get("PostID"))));
                    }
                }
                searcher.Dispose();
                directoryPronadjeniClanciTagovi.Dispose();
                return postovi;
            }
            else
            {
                searcher.Dispose();
                directoryPronadjeniClanciTagovi.Dispose();
                return postovi;
            }
        }
Ejemplo n.º 13
0
        // search methods
        public static IEnumerable<LuceneSearchModel> GetAllIndexRecords()
        {
            // validate search index
            if (!System.IO.Directory.EnumerateFiles(_luceneDir).Any()) return new List<LuceneSearchModel>();

            // set up lucene searcher
            var searcher = new IndexSearcher(_directory, false);
            var reader = IndexReader.Open(_directory, false);
            searcher.SetDefaultFieldSortScoring(true, true);
            var docs = new List<Document>();
            var term = reader.TermDocs();
            while (term.Next()) docs.Add(searcher.Doc(term.Doc));
            reader.Dispose();
            searcher.Dispose();
            return _mapLuceneToDataList(docs);
        }
		// search methods
		public static IEnumerable<SampleData> GetAllIndexRecords() {
			// validate search index
			if (!System.IO.Directory.EnumerateFiles(_luceneDir).Any()) return new List<SampleData>();

			// set up lucene searcher
			var searcher = new IndexSearcher(_directory, false);
			var reader = IndexReader.Open(_directory, false);
			var docs = new List<Document>();
			var term = reader.TermDocs();
      // v 2.9.4: use 'term.Doc()'
      // v 3.0.3: use 'term.Doc'
			while (term.Next()) docs.Add(searcher.Doc(term.Doc));
			reader.Dispose();
			searcher.Dispose();
			return _mapLuceneToDataList(docs);
		}
Ejemplo n.º 15
0
        public static IEnumerable<LuceneSearchEO> GetAllIndexRecords(LuceneSearchType searchType)
        {
            string _luceneDir = getLuceneDirectory(searchType);
            if (!System.IO.Directory.EnumerateFiles(_luceneDir).Any()) return new List<LuceneSearchEO>();

            // set up lucene searcher
            var searcher = new IndexSearcher(getFSDirectory(searchType), false);
            var reader = IndexReader.Open(getFSDirectory(searchType), false);
            var docs = new List<Document>();
            var term = reader.TermDocs();
            // v 2.9.4: use 'term.Doc()'
            // v 3.0.3: use 'term.Doc'
            while (term.Next()) docs.Add(searcher.Doc(term.Doc));
            reader.Dispose();
            searcher.Dispose();
            return _mapLuceneToDataList(docs);
        }
Ejemplo n.º 16
0
        public List <Item> Search2(string keyWord)
        {
            //string strAnalyzerType = comboBox2.SelectedItem.ToString();
            string strAnalyzerType = "StandardAnalyzer";

            if (comboBox2.SelectedItem != null)
            {
                strAnalyzerType = comboBox2.SelectedItem.ToString();
            }
            string strType = "A";

            if (textBox3.Text != "")
            {
                strType = textBox3.Text.ToString();
            }
            FSDirectory dir     = FSDirectory.Open(indexLocation);
            List <Item> results = new List <Item>();

            Lucene.Net.Util.Version      AppLuceneVersion = Lucene.Net.Util.Version.LUCENE_30;
            Lucene.Net.Analysis.Analyzer analyzer         = AnalyzerHelper.GetAnalyzerByName(strAnalyzerType);

            Lucene.Net.QueryParsers.MultiFieldQueryParser parser = new Lucene.Net.QueryParsers.MultiFieldQueryParser(AppLuceneVersion, new string[] { "title", "content" }, analyzer);
            /////////////////////////////////////////////////
            BooleanQuery query     = new BooleanQuery();
            Query        queryType = new TermQuery(new Term("title", strType));
            Query        queryKey  = new TermQuery(new Term("content", keyWord));

            query.Add(queryType, Occur.MUST);
            query.Add(queryKey, Occur.MUST);
            Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir);
            TopDocs topdocs = searcher.Search(query, 100);

            Lucene.Net.Search.ScoreDoc[] hits = topdocs.ScoreDocs;

            foreach (var hit in hits)
            {
                var foundDoc = searcher.Doc(hit.Doc);
                results.Add(new Item {
                    title = foundDoc.Get("title"), content = foundDoc.Get("content")
                });
            }
            searcher.Dispose();
            return(results);
        }
Ejemplo n.º 17
0
        public DataTable Search(Analyzer analyzer, string keyword)
        {
            if (string.IsNullOrEmpty(keyword))
            {
                throw new ArgumentException("keyword");
            }

            // 计时
            Stopwatch watch = Stopwatch.StartNew();

            // 设置
            int numHits = 10;
            bool docsScoredInOrder = true;
            bool isReadOnly = true;

            // 创建Searcher
            FSDirectory fsDir = new SimpleFSDirectory(new DirectoryInfo(_indexerFolder));
            IndexSearcher indexSearcher = new IndexSearcher(IndexReader.Open(fsDir, isReadOnly));

            TopScoreDocCollector collector = TopScoreDocCollector.Create(numHits, docsScoredInOrder);
            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, LuceneConfig.Field_ContentByPage, analyzer);
            Query query = parser.Parse(keyword);

            indexSearcher.Search(query, collector);

            //Console.WriteLine(collector.TotalHits);
            var result = collector.TopDocs().ScoreDocs;

            DataTable dt = ConvertToDataTable(indexSearcher, result);

            // dispose IndexSearcher
            indexSearcher.Dispose();

            watch.Stop();
            WriteLog("总共耗时{0}毫秒", watch.ElapsedMilliseconds);
            WriteLog("总共找到{0}个文件", result.Count());

            return dt;
        }
        private static IEnumerable<BaseCollectionItem> GetAllIndexRecords()
        {
            // validate search index
            if (!System.IO.Directory.EnumerateFiles(LuceneService.LuceneDir).Any()) return new List<BaseCollectionItem>();

            // set up lucene searcher
            var searcher = new IndexSearcher(LuceneService.Directory, false);
            var reader = IndexReader.Open(LuceneService.Directory, false);
            var docs = new List<Document>();
            var term = reader.TermDocs();
            while (term.Next()) docs.Add(searcher.Doc(term.Doc));
            reader.Dispose();
            searcher.Dispose();
            return MapLuceneToDataList(docs);
        }
Ejemplo n.º 19
0
 //partially taken from http://www.codeproject.com/Articles/320219/Lucene-Net-ultra-fast-search-for-MVC-or-WebForms
 //START
 private IEnumerable<FileToIndex> _search(string keywords, out int count, string field = "")
 {
     if (string.IsNullOrEmpty(keywords.Replace("*", "").Replace("?", "")))
     {
         count = 0;
         return new List<FileToIndex>();
     }
     using (var searcher = new IndexSearcher(_directory))
     using (var analyzer = new Lucene.Net.Analysis.Ru.RussianAnalyzer(Version.LUCENE_30))
     {
         if (!string.IsNullOrEmpty(field))
         {
             var parser = new QueryParser(Version.LUCENE_30, field, analyzer);
             var queryForField = parseQuery(keywords, parser);
             var docs = searcher.Search(queryForField, 100);
             count = docs.TotalHits;
             var samples = _convertDocs(docs.ScoreDocs, searcher);
             searcher.Dispose();
             return samples;
         }
         else
         {
             var parser = new MultiFieldQueryParser
                 (Version.LUCENE_30, new[] { "Title", "Authors", "Description", "Text", "Discipline" }, analyzer);
             var queryForField = parseQuery(keywords, parser);
             var docs = searcher.Search(queryForField, null, 100, Sort.RELEVANCE);
             count = docs.TotalHits;
             var samples = _convertDocs(docs.ScoreDocs, searcher);
             searcher.Dispose();
             return samples;
         }
     }
 }
Ejemplo n.º 20
0
 private void CleanUpSearch()
 {
     searcher.Dispose();
 }
        private static IEnumerable<BaseCollectionItem> SearchLucene(string searchQuery, string searchField = "")
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<BaseCollectionItem>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(LuceneService.Directory, false))
            {
                var hits_limit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                // search by single field
                if (!string.IsNullOrEmpty(searchField))
                {
                    var parser = new QueryParser(Version.LUCENE_30, searchField, analyzer);
                    var query = ParseQuery(searchQuery, parser);
                    var hits = searcher.Search(query, hits_limit).ScoreDocs;
                    var results = MapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
                // search by multiple fields (ordered by RELEVANCE)
                else
                {
                    var parser = new MultiFieldQueryParser
                        (Version.LUCENE_30, new[] { "Id", "TableId", "Data","ItemProcessed", "CreatedDate" }, analyzer);
                    var query = ParseQuery(searchQuery, parser);
                    var hits = searcher.Search(query, null, hits_limit, Sort.RELEVANCE).ScoreDocs;
                    var results = MapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Closes the index after searching
 /// </summary>
 public void CleanUpSearch()
 {
     searcher.Dispose();
 }
Ejemplo n.º 23
0
        // main search method
        private static IEnumerable<Creative> _search(string searchQuery)
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<Creative>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(_directory, false))
            {
                var hits_limit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                var parser = new MultiFieldQueryParser
                    (Version.LUCENE_30, new[] { "Id", "Title", "Description", "Name", "Text"}, analyzer);
                var query = ParseQuery(searchQuery, parser);
                var hits = searcher.Search(query, null, hits_limit, Sort.INDEXORDER).ScoreDocs;
                var results = _mapLuceneToDataList(hits, searcher);
                analyzer.Close();
                searcher.Dispose();
                return results;

            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// All the data indexed.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<News> GetAllData()
        {
            if (!System.IO.Directory.EnumerateFiles(LuceneDir).Any())
            {
                return new List<News>();
            }

            var searcher = new IndexSearcher(Directory, false);
            var reader = IndexReader.Open(Directory, false);
            var docs = new List<Document>();
            var term = reader.TermDocs();

            while (term.Next())
            {
                docs.Add(searcher.Doc(term.Doc));
            }

            reader.Dispose();
            searcher.Dispose();
            return MapLuceneToDataList(docs);
        }
Ejemplo n.º 25
0
        static void Search(string keyword)
        {
            IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(INDEX_DIR), true);
            QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "body", analyzer);
            Query query = qp.Parse(keyword); //2008年底  
            Console.WriteLine("query> {0}", query);


            TopDocs tds = searcher.Search(query, 10);
            Console.WriteLine("TotalHits: " + tds.TotalHits);
            foreach (ScoreDoc sd in tds.ScoreDocs)
            {
                Console.WriteLine(sd.Score);
                Document doc = searcher.Doc(sd.Doc);
                Console.WriteLine(doc.Get("body"));
            }

            searcher.Dispose();
        }
Ejemplo n.º 26
0
        public static List<Post> getClanciPretrage(string recenica)
        {
            if (recenica != "")
            {

                Directory directoryPronadjeniClanci = Data.Lucene.Indexing.GetDirectoryClanci();
                Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
                IndexReader indexReader = IndexReader.Open(directoryPronadjeniClanci, true);
                Searcher searcher = new IndexSearcher(indexReader);

                //var queryParser = new QueryParser(Version.LUCENE_30, "Naslov", analyzer);
                var queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { "Naslov", "Sazetak", "Sadrzaj", "Tagovi" }, analyzer);
                var query = queryParser.Parse(recenica.Trim()); // Rastavljanje rečenice na rijeci

                TopDocs pronadjeno = searcher.Search(query, indexReader.MaxDoc);
                List<Post> postovi = new List<Post>();
                var hits = pronadjeno.ScoreDocs;
                foreach (var hit in hits)
                {
                    var documentFromSearcher = searcher.Doc(hit.Doc);
                    using (TriglavBL temp = new TriglavBL())
                    {
                        postovi.Add(temp.getClanakByID(Convert.ToInt32(documentFromSearcher.Get("id"))));
                    }
                }

                searcher.Dispose();
                directoryPronadjeniClanci.Dispose();
                return postovi;
            }
            else return null;
        }
Ejemplo n.º 27
0
 public void CleanUpSearch() // Cleans up searcher
 {
     searcher.Dispose();
 }
        public void Search(string keyword)
        {
            IndexReader reader = null;
            IndexSearcher searcher = null;
            try
            {
                reader = IndexReader.Open(FSDirectory.Open(new DirectoryInfo(indexDirectory)), true);
                searcher = new IndexSearcher(reader);
                //创建查询
                PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(analyzer);
                wrapper.AddAnalyzer("FileName", analyzer);
                wrapper.AddAnalyzer("Author", analyzer);
                wrapper.AddAnalyzer("Content", analyzer);
                string[] fields = { "FileName", "Author", "Content" };

                QueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, fields, wrapper);
                Query query = parser.Parse(keyword);
                TopScoreDocCollector collector = TopScoreDocCollector.Create(NumberHits, true);

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

                int numTotalHits = collector.TotalHits;

                //以后就可以对获取到的collector数据进行操作
                for (int i = 0; i < hits.Count(); i++)
                {
                    var hit = hits[i];
                    Document doc = searcher.Doc(hit.Doc);
                    Field fileNameField = doc.GetField("FileName");
                    Field authorField = doc.GetField("Author");
                    Field pathField = doc.GetField("Path");

                }
            }
            finally
            {
                if (searcher != null)
                    searcher.Dispose();

                if (reader != null)
                    reader.Dispose();
            }
        }
Ejemplo n.º 29
0
        private void search()
        {
            DateTime start = DateTime.Now;
            // create the result DataTable
            this.Results.Columns.Add("title", typeof(string));
            this.Results.Columns.Add("sample", typeof(string));
            this.Results.Columns.Add("path", typeof(string));
            this.Results.Columns.Add("url", typeof(string));
            this.Results.Columns.Add("Type", typeof(string));

            // create the searcher
            // index is placed in "index" subdirectory
            string indexDirectory = Server.MapPath("~/App_Data/index");

            var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
            //   List<string> STOP_WORDS =  StopAnalyzer.ENGLISH_STOP_WORDS_SET.ToList<string>();
            IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(indexDirectory));
            BooleanQuery bquery = new BooleanQuery();
            //var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "text", analyzer);
            List<string> SearchTerm = new List<string> { "text", "path", "title", "Extension", "EXTPRP" };
            List<string> Projects = new List<string>();
            if (Session["ProjectList"] != null)
            {
                Projects = (List<string>)Session["ProjectList"];
            }

            List<string> allType = new List<string> { "A", "B", "C" };
            if (this.Request.QueryString["Page"] != null)
            {
                if (allType.Contains(this.Request.QueryString["Page"].ToString()))
                {
                    allType.Remove(this.Request.QueryString["Page"]);
                    foreach (string type in allType)
                    {
                        TermQuery termq1 = new TermQuery(new Term("EXTPRP", type));
                        bquery.Add(termq1, Occur.MUST_NOT);
                        FuzzyQuery termq = new FuzzyQuery(new Term("EXTPRP", type), 0.5f, 0);
                        bquery.Add(termq, Occur.MUST_NOT);
                    }
                }
            }

            //Query query = parser.Parse(this.Query);
            //foreach (string term in SearchTerm)
            //{
            //    if (term == "title")
            //    {
            //        TermQuery termq = new TermQuery(new Term(term, this.Query));
            //        termq.Boost = 50f;
            //        bquery.Add(termq, Occur.SHOULD);
            //    }
            //    else
            //    {
            //        TermQuery termq = new TermQuery(new Term(term, this.Query));
            //        termq.Boost = 5f;
            //        bquery.Add(termq, Occur.SHOULD);
            //    }

            //}

            foreach (string term in SearchTerm)
            {
                if (term == "title")
                {
                    TermQuery termq = new TermQuery(new Term(term, this.Query));
                    termq.Boost = 5f;
                    bquery.Add(termq, Occur.SHOULD);
                }
                else
                {
                    FuzzyQuery termq = new FuzzyQuery(new Term(term, this.Query), 0.5f, 0);
                    termq.Boost = 0.1f;
                    bquery.Add(termq, Occur.SHOULD);
                }
            }

            //foreach (string project in Projects)
            //{
            //    TermQuery termq1 = new TermQuery(new Term("Project", project));
            //    bquery.Add(termq1, Occur.MUST_NOT);

            //}

            //foreach (string project in Projects.Distinct())
            //{
            //    TermQuery termq1 = new TermQuery(new Term("path", project));
            //    bquery.Add(termq1, Occur.MUST);
            //    FuzzyQuery termq = new FuzzyQuery(new Term("path", project), 0.5f, 0);
            //    bquery.Add(termq, Occur.MUST);
            //}

            //bquery.Add(new TermQuery(new Term("Project", "DEV")), Occur.SHOULD);

            //List<ScoreDoc> TempArrList = new List<ScoreDoc>();

            TopDocs hits = searcher.Search(bquery, null, 10000);

            //TopDocs hits = new TopDocs(TempArrList.Count(), TempArrList.ToArray(), hitsWithText.MaxScore);
            //hits.ScoreDocs.CopyTo(hits.ScoreDocs, 0);
            //hits.ScoreDocs = hits.ScoreDocs.OrderBy(obj => searcher.Doc(obj.Doc).Get("path")).ToArray();

            if (Projects.Count() != 0)
            {
                hits.ScoreDocs = hits.ScoreDocs.Where(obj => Projects.Contains(Path.GetDirectoryName(searcher.Doc(obj.Doc).Get("path")))).Distinct().ToArray();
            }

            //foreach (string project in Projects.Distinct())
            //{
            //    //hits.ScoreDocs = hits.ScoreDocs.Where(obj => Regex.IsMatch(searcher.Doc(obj.Doc).Get("path").Replace(@"\", @"\\"), @".*" + project.Replace(@"\", @"\\") + ".*")).ToArray();
            //    string s = Path.GetDirectoryName("\\SAGITEC-1629\\Soogle\\CARS\\bhagyashree.txt");
            //    hits.ScoreDocs = hits.ScoreDocs.Where(obj => Path.GetDirectoryName(searcher.Doc(obj.Doc).Get("path")).Contains(project)).ToArray();
            //}

            this.total = hits.ScoreDocs.Count();

            this.startAt = InitStartAt();

            int resultsCount = Math.Min(total, this.maxResults + this.startAt);

            // create highlighter
            IFormatter formatter = new SimpleHTMLFormatter("<span style=\"font-weight:bold;background-color:yellow;\">", "</span>");
            SimpleFragmenter fragmenter = new SimpleFragmenter(200);
            QueryScorer scorer = new QueryScorer(bquery);
            Highlighter highlighter = new Highlighter(formatter, scorer);
            highlighter.TextFragmenter = fragmenter;

            int j = 0;

            for (int i = startAt; i < resultsCount; i++)
            {
                Document doc = searcher.Doc(hits.ScoreDocs[i].Doc);
                String path = doc.Get("path");
                string getExtension = doc.Get("Extension");

                TokenStream stream = analyzer.TokenStream("", new StringReader(doc.Get("text")));
                String sample = "";
                try
                {
                    string document = doc.Get("text");
                    if (getExtension.ToLower() == ".png" || getExtension.ToLower() == ".jpg" || getExtension.ToLower() == ".gif" || getExtension.ToLower() == ".bmp")
                    {
                        sample = "";
                    }
                    else
                    {
                        sample = highlighter.GetBestFragment(stream, document);//, 2, "...");
                    }

                }
                catch (Exception ex)
                {
                }

                // create a new row with the result data
                DataRow row = this.Results.NewRow();
                row["title"] = doc.Get("title");
                row["path"] = "http://sagitec-1629/KNBASE/" + path.Replace(@"\", "/").Replace("//SAGITEC-1629/Soogle/", "");
                row["url"] = "http://sagitec-1629/KNBASE/" + path.Replace(@"\", "/").Replace("//SAGITEC-1629/Soogle/", "");
                row["sample"] = sample;
                if (path.Contains('.'))
                {
                    row["Type"] = GetMIMEType(path);
                }
                //if (!Projects.Contains(doc.Get("Project")) || !allType.Contains(doc.Get("EXTPRP")))
                //{
                this.Results.Rows.Add(row);
                //}
                j++;

            }

            Repeater1.DataSource = Results;
            Repeater1.DataBind();

            searcher.Dispose();

            // result information
            this.duration = DateTime.Now - start;
            this.fromItem = startAt + 1;
            this.toItem = Math.Min(startAt + maxResults, total);
        }
Ejemplo n.º 30
0
        // main search method
        private static IEnumerable<LuceneSearchModel> _search(string searchQuery, int amountToTake, string searchField = "")
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<LuceneSearchModel>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(_directory, false))
            {
                const int hitsLimit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                // search by single field
                if (!string.IsNullOrEmpty(searchField))
                {
                    var parser = new QueryParser(Version.LUCENE_30, searchField, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    searcher.SetDefaultFieldSortScoring(true, true);
                    var hits = searcher.Search(query, hitsLimit).ScoreDocs;
                    var results = _mapLuceneToDataList(hits, searcher, amountToTake);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
                // search by multiple fields (ordered by RELEVANCE)
                else
                {
                    var parser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { AppConstants.LucId, AppConstants.LucTopicName, AppConstants.LucTopicTags, AppConstants.LucPostContent }, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    searcher.SetDefaultFieldSortScoring(true, true);
                    var hits = searcher.Search(query, null, hitsLimit, Sort.INDEXORDER).ScoreDocs;
                    var results = _mapLuceneToDataList(hits, searcher, amountToTake);
                    analyzer.Close();
                    searcher.Dispose();
                    return results;
                }
            }
        }
        public IEnumerable<string> Search(IDictionary<string, string> matches)
        {
            var results = new List<string>();
            var indexSearcher = new IndexSearcher(_directory, true);

            var booleanQuery = new BooleanQuery();

            foreach (var match in matches)
            {
                booleanQuery.Add(new TermQuery(new Term(match.Key, match.Value)), BooleanClause.Occur.MUST);    
            }

            try
            {
                var hits = indexSearcher.Search(booleanQuery);
                var numHits = hits.Length();

                for (var i = 0; i < numHits; ++i)
                {
                    var doc = hits.Doc(i);
                    var url = doc.Get("Url");
                    results.Add(url);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn(ex);
            }
            finally
            {
                indexSearcher.Close();
                indexSearcher.Dispose();
            }

            return results;
        }
Ejemplo n.º 32
0
        public void Search(Analyzer analyzer, string keyword)
        {
            if (string.IsNullOrEmpty(keyword))
            {
                throw new ArgumentException("content");
            }

            // 计时
            Stopwatch watch = new Stopwatch();
            watch.Start();

            // 设置
            int numHits = 10;
            bool docsScoredInOrder = true;
            bool isReadOnly = true;

            // 创建Searcher
            FSDirectory fsDir = new SimpleFSDirectory(new DirectoryInfo(_indexerFolder));
            IndexSearcher indexSearcher = new IndexSearcher(IndexReader.Open(fsDir, isReadOnly));

            TopScoreDocCollector collector = TopScoreDocCollector.Create(numHits, docsScoredInOrder);
            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, Config.Field_Content, analyzer);
            Query query = parser.Parse(keyword);

            indexSearcher.Search(query, collector);

            //Console.WriteLine(collector.TotalHits);
            var result = collector.TopDocs().ScoreDocs;

            watch.Stop();
            Console.WriteLine("总共耗时{0}毫秒", watch.ElapsedMilliseconds);
            Console.WriteLine("总共找到{0}个文件", result.Count());

            foreach (var docs in result)
            {
                Document doc = indexSearcher.Doc(docs.Doc);
                Console.WriteLine("得分:{0},文件名:{1}", docs.Score, doc.Get(Config.Field_Name));
            }

            indexSearcher.Dispose();

            //BooleanQuery booleanQuery = new BooleanQuery();

            //QueryParser parser1 = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, Config.Field_Path, analyzer);
            //Query query1 = parser1.Parse(path);
            //parser1.DefaultOperator = QueryParser.Operator.AND;
            //booleanQuery.Add(query1, Occur.MUST);

            ////QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, Config.Field_Content, analyzer);
            ////Query query = parser.Parse(content);
            ////parser.DefaultOperator = QueryParser.Operator.AND;
            ////booleanQuery.Add(query, Occur.MUST);



            ////var queryParserFilePath = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new string[] { Config.Field_FilePath }, analyzer);
            ////query.Add(queryParserFilePath.Parse(path), Occur.SHOULD);

            ////var queryParserContent = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new string[] { Config.Field_Content}, analyzer);
            ////query.Add(queryParserContent.Parse(content), Occur.MUST);

            //FSDirectory fsDir = new SimpleFSDirectory(new DirectoryInfo(_indexerFolder));
            //bool isReadOnly = true;
            //IndexSearcher indexSearcher = new IndexSearcher(IndexReader.Open(fsDir, isReadOnly));
            ////TopDocs result = indexSearcher.Search(booleanQuery, 10);
            //Sort sort = new Sort(new SortField(Config.Field_Path, SortField.STRING, true));
            //var result = indexSearcher.Search(booleanQuery, (Filter)null, 10 * 1, sort);

        }
Ejemplo n.º 33
0
        /// <summary>
        ///     Searches the datasource using the specified criteria. Criteria is parsed by the query builder specified by
        ///     <typeparamref />
        ///     .
        /// </summary>
        /// <param name="scope">Name of the application.</param>
        /// <param name="criteria">The criteria.</param>
        /// <returns></returns>
        /// <exception cref="VirtoCommerce.SearchModule.Data.Providers.Lucene.LuceneSearchException"></exception>
        public virtual ISearchResults Search(string scope, ISearchCriteria criteria)
        {
            ISearchResults result;

            var directoryInfo = new DirectoryInfo(GetDirectoryPath(GetFolderName(scope, criteria.DocumentType)));

            if (directoryInfo.Exists)
            {
                var dir = FSDirectory.Open(directoryInfo);
                var searcher = new IndexSearcher(dir);

                var q = (QueryBuilder)QueryBuilder.BuildQuery(criteria);

                // filter out empty value
                var filter = q.Filter.ToString().Equals("BooleanFilter()") ? null : q.Filter;

                Debug.WriteLine("Search Lucene Query:{0}", q.ToString());

                TopDocs docs;

                try
                {
                    var numDocs = criteria.StartingRecord + criteria.RecordsToRetrieve;

                    if (criteria.Sort != null)
                    {
                        var fields = criteria.Sort.GetSort();

                        docs = searcher.Search(
                            q.Query,
                            filter,
                            numDocs,
                            new Sort(
                                fields.Select(field => new SortField(field.FieldName, field.DataType, field.IsDescending))
                                    .ToArray()));
                    }
                    else
                    {
                        docs = searcher.Search(q.Query, filter, numDocs);
                    }
                }
                catch (Exception ex)
                {
                    throw new LuceneSearchException("Search exception", ex);
                }

                var results = new LuceneSearchResults(searcher, searcher.IndexReader, docs, criteria, q.Query);

                // Cleanup here
                searcher.IndexReader.Dispose();
                searcher.Dispose();
                result = results.Results;
            }
            else
            {
                result = new SearchResults(criteria, null);
            }

            return result;
        }
Ejemplo n.º 34
0
        public static void SearchSomething(string wordToSearch)
        {
            Directory directory = FSDirectory.Open(new
            System.IO.DirectoryInfo("E:\\GitHub\\LuceneIndex"));

            Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);

            QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "postBody", analyzer);

            Query query = parser.Parse(wordToSearch+"*");

            //Setup searcher
            IndexSearcher searcher = new IndexSearcher(directory);
            //Do the search
            //Hits hits = searcher.Search(query);

            //var searcher = new IndexSearcher(directory, true);

            Lucene.Net.Search.Query query1 = parser.Parse(wordToSearch);
            Lucene.Net.Search.Searcher searcher1 =
              new Lucene.Net.Search.IndexSearcher
            (Lucene.Net.Index.IndexReader.Open(directory, true));

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

            searcher1.Search(query1, collector);
            ScoreDoc[] hits = collector.TopDocs().ScoreDocs;

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

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

                string result = "Score: " + score.ToString() +
                                " Field: " + doc.Get("postBody") +
                                " Field2: " + doc.Get("TERM");

            }

            //QueryParser parser = new QueryParser("postBody", analyzer);
            //Query query = parser.Parse("text");

            TopDocs topDocs = searcher.Search(query, 20);

            int results = topDocs.ScoreDocs.Length;
               // int results = hits.Length();

            //var parser = BuildQueryParser();
            //var query = parser.Parse(searchQuery);
            var Searcher = searcher;

            TopDocs hits1 = searcher.Search(query, null, 20);
            //IList<SearchResult> result = new List<SearchResult>();
            //float scoreNorm = 1.0f / hits.GetMaxScore();

            Console.WriteLine("Found {0} results", results);

            ScoreDoc scoreDoc;
            for (int i = 0; i < topDocs.TotalHits; i++)
            {
                Document doc = searcher.Doc(topDocs.ScoreDocs[i].Doc);
                //Document doc = searcher.Doc(td.scoreDocs[i].doc);

                 //scoreDoc = topDocs.ScoreDocs[i];

                //float score = scoreDoc.Score;

                //int docId = scoreDoc.Doc;

               // Document doc = searcher.Doc(docId);

                //Console.WriteLine("Result num {0}, score {1}", i + 1, score);

                //Console.WriteLine("ID: {0}", doc.Get("id"));

                //Console.WriteLine("Text found: {0}\r\n", doc.Get("postBody"));
                string a = doc.Get("postBody");
            }

            searcher.Dispose();

            directory.Dispose();
        }
Ejemplo n.º 35
0
 public void CleanSearcher()
 {
     searcher.Dispose();//dispose searcher so that more space can be released.
 }
Ejemplo n.º 36
0
        public void Test_CacheDirectory_Create_And_Read_Index()
        {
            const string TEXT = "This is the text to be indexed.";

            // create the index
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);

            // remove
            var controlDirectory = CreateRamDirectory();
            // end remove
            var testDirectory = directory;

            IndexText(testDirectory, TEXT);

            // search the index
            IndexSearcher indexSearcher = new IndexSearcher(testDirectory, true);
            QueryParser parser = new QueryParser(Version.LUCENE_30, "fieldname", analyzer);
            Query query = parser.Parse("text");
            ScoreDoc[] hits = indexSearcher.Search(query, null, 1000).ScoreDocs;
            Assert.AreEqual(1, hits.Length);

            // iterate through the results
            string expectedText = string.Copy(TEXT);
            for(int i=0;i<hits.Length;i++)
            {
                Document hitDocument = indexSearcher.Doc(hits[i].Doc);
                Assert.AreEqual(hitDocument.Get("fieldname"), expectedText);
            }
            indexSearcher.Dispose();
            directory.Dispose();
        }
Ejemplo n.º 37
0
        private static PagedList<LuceneSearchModel> _search(string searchQuery, int pageIndex, int pageSize)
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return null;
            // set up lucene searcher
            using (var searcher = new IndexSearcher(_directory, false))
            {
                const int hitsLimit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                var parser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { AppConstants.LucId, AppConstants.LucTopicName, AppConstants.LucTopicTags, AppConstants.LucPostContent }, analyzer);
                var query = parseQuery(searchQuery, parser);
                searcher.SetDefaultFieldSortScoring(true, true);
                var hits = searcher.Search(query, null, hitsLimit, Sort.INDEXORDER).ScoreDocs;
                var results = _mapLuceneToDataList(hits, searcher, pageIndex, pageSize);
                analyzer.Close();
                searcher.Dispose();
                return results;
            }
        }
Ejemplo n.º 38
0
        private static IEnumerable<Offer> _search(string searchQuery, string searchField = "")
        {
            // validation
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) return new List<Offer>();

            // set up lucene searcher
            using (var searcher = new IndexSearcher(_directory, false))
            {
                var hits_limit = 1000;
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);
                IEnumerable<Offer> results;
                // search by single field
                if (!string.IsNullOrEmpty(searchField))
                {
                    var parser = new QueryParser(Version.LUCENE_30, searchField, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    var hits = searcher.Search(query, hits_limit).ScoreDocs;
                    results = _mapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                }
                // search by multiple fields (ordered by RELEVANCE)
                else
                {
                    var parser = new MultiFieldQueryParser
                        (Version.LUCENE_30, new[] { "Id", "Name", "Description" }, analyzer);
                    var query = parseQuery(searchQuery, parser);
                    var hits = searcher.Search
                    (query, null, hits_limit, Sort.RELEVANCE).ScoreDocs;
                    results = _mapLuceneToDataList(hits, searcher);
                    analyzer.Close();
                    searcher.Dispose();
                }
                var OfferCollection = new List<Offer>();
                var _repo = new SellYourTimeRepository();
                foreach (Offer result in results)
                {
                    var Offer = _repo.FindOfferById(result.Id);
                    if (Offer != null)
                        OfferCollection.Add(Offer);
                }
                return OfferCollection;
            }
        }
        private IEnumerable<Project> search(string searchQuery, string searchField = "")
        {
            if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", "")))
                return new List<Project>();

            using (var searcher = new IndexSearcher(Directory, false))
            {
                var analyzer = new StandardAnalyzer(Version.LUCENE_30);

                var parser = new MultiFieldQueryParser(Version.LUCENE_30, new[]
                {
                    SearchingFields.Id.ToString(),
                    SearchingFields.Name.ToString()
                }, analyzer);
                var query = ParseQuery(searchQuery, parser);
                var docs = searcher.Search(query, null, HitsLimits, Sort.RELEVANCE).ScoreDocs;
                var results = MapSearchResults(docs, searcher);
                analyzer.Close();
                searcher.Dispose();

                return results;
            }
        }
Ejemplo n.º 40
0
        public static DataTable searchPitanja(string pretraga)
        {
            DataTable ResultsPitanja = new DataTable();
            // create the searcher
            // index is placed in "index" subdirectory
            string indexDirectory = "J:/Triglav_Web_App/Triglav/Web/Lucene/Pitanja";
            var analyzer = new StandardAnalyzer(Version.LUCENE_30);
            IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(indexDirectory));

            // parse the query, "text" is the default field to search
            var parser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { "Naslov", "Sadrzaj", "Tagovi" }, analyzer);
            //var parser = new QueryParser(Version.LUCENE_30, "Sadrzaj", analyzer);
            Query query = parser.Parse(pretraga);

            //// create the result DataTable
            ResultsPitanja.Columns.Add("id", typeof(Int32));
            ResultsPitanja.Columns.Add("Naslov", typeof(string));
            ResultsPitanja.Columns.Add("Sadrzaj", typeof(string));
            ResultsPitanja.Columns.Add("Tagovi", typeof(string));
            ResultsPitanja.Columns.Add("DatumKreiranja", typeof(DateTime));
            ResultsPitanja.Columns.Add("DatumZadnjeIzmjene", typeof(DateTime));
            ResultsPitanja.Columns.Add("DatumZadnjeAktivnosti", typeof(DateTime));
            ResultsPitanja.Columns.Add("DatumZatvaranjaPosta", typeof(DateTime));
            ResultsPitanja.Columns.Add("PrihvaceniOdgovori", typeof(Int32));
            ResultsPitanja.Columns.Add("BrojOdgovora", typeof(Int32));
            ResultsPitanja.Columns.Add("BrojKomentara", typeof(Int32));
            ResultsPitanja.Columns.Add("BrojOmiljenih", typeof(Int32));
            ResultsPitanja.Columns.Add("BrojPregleda", typeof(Int32));
            ResultsPitanja.Columns.Add("BrojPoena", typeof(Int32));
            ResultsPitanja.Columns.Add("VlasnikID", typeof(Int32));
            ResultsPitanja.Columns.Add("VlasnikNadimak", typeof(string));
            ResultsPitanja.Columns.Add("PromijenioID", typeof(Int32));
            ResultsPitanja.Columns.Add("RoditeljskiPostID", typeof(Int32));
            //Results.Columns.Add("PodKategorija", typeof(Int32));
            ResultsPitanja.Columns.Add("PostVrsta", typeof(Int32));
            // ResultsPitanja.Columns.Add("SlikaURL", typeof(string));
            ResultsPitanja.Columns.Add("temp", typeof(string));
            ResultsPitanja.Columns.Add("Likes", typeof(Int32));
            ResultsPitanja.Columns.Add("Unlikes", typeof(Int32));
            ResultsPitanja.Columns.Add("Sazetak", typeof(string));
            ResultsPitanja.Columns.Add("BrojRangiranja", typeof(Int32));
            ResultsPitanja.Columns.Add("PrihvacenaIzmjena", typeof(Int32));
            ResultsPitanja.Columns.Add("Podnaslov", typeof(string));
            ResultsPitanja.Columns.Add("Broj.Razgovora", typeof(Int32));
            ResultsPitanja.Columns.Add("sample", typeof(string));

            // search
            TopDocs hits = searcher.Search(query, 5);

            //E this.total = hits.TotalHits;

            // create highlighter
            IFormatter formatter = new SimpleHTMLFormatter("<span style=\"font-weight:bold; background-color: #e5ecf9; \">", "</span>");
            SimpleFragmenter fragmenter = new SimpleFragmenter(80);
            QueryScorer scorer = new QueryScorer(query);
            Highlighter highlighter = new Highlighter(formatter, scorer);
            highlighter.TextFragmenter = fragmenter;

            for (int i = 0; i < hits.ScoreDocs.Count(); i++)
            {
                // get the document from index
                Document doc = searcher.Doc(hits.ScoreDocs[i].Doc);

                TokenStream stream = analyzer.TokenStream("", new StringReader(doc.Get("Sadrzaj")));
                String sample = highlighter.GetBestFragments(stream, doc.Get("Sadrzaj"), 3, "...");

                //String path = doc.Get("path");

                // create a new row with the result data
                DataRow rowPitanja = ResultsPitanja.NewRow();

                rowPitanja["id"] = doc.Get("id");
                rowPitanja["Naslov"] = doc.Get("Naslov");
                rowPitanja["Sadrzaj"] = sample; //doc.Get("Sadrzaj");
                rowPitanja["Tagovi"] = doc.Get("Tagovi");
                rowPitanja["DatumKreiranja"] = doc.Get("DatumKreiranja");
                rowPitanja["DatumZadnjeIzmjene"] = doc.Get("DatumZadnjeIzmjene");
                rowPitanja["DatumZadnjeAktivnosti"] = doc.Get("DatumZadnjeAktivnosti");
                //row["DatumZatvaranjaPosta"] = doc.Get("DatumZatvaranjaPosta");
                rowPitanja["PrihvaceniOdgovori"] = doc.Get("PrihvaceniOdgovori");
                rowPitanja["BrojOdgovora"] = doc.Get("BrojOdgovora");
                rowPitanja["BrojKomentara"] = doc.Get("BrojKomentara");
                rowPitanja["BrojOmiljenih"] = doc.Get("BrojOmiljenih");
                rowPitanja["BrojPregleda"] = doc.Get("BrojPregleda");
                rowPitanja["BrojPoena"] = doc.Get("BrojPoena");
                //row["VlasnikID"] = doc.Get("VlasnikID");
                rowPitanja["VlasnikNadimak"] = doc.Get("VlasnikNadimak");
                //row["PromijenioID"] = doc.Get("PromijenioID");
                //row["RoditeljskiPostID"] = doc.Get("RoditeljskiPostID");
                //row["PodKategorija"] = doc.Get("PodKategorija");
                rowPitanja["PostVrsta"] = doc.Get("PostVrsta");
                //rowPitanja["SlikaURL"] = doc.Get("SlikaURL");
                //row["temp"] = doc.Get("temp");
                rowPitanja["Likes"] = doc.Get("Likes");
                rowPitanja["Unlikes"] = doc.Get("Unlikes");
                rowPitanja["Sazetak"] = doc.Get("Sazetak");
                rowPitanja["BrojRangiranja"] = doc.Get("BrojRangiranja");
                rowPitanja["PrihvacenaIzmjena"] = doc.Get("PrihvacenaIzmjena");
                rowPitanja["Podnaslov"] = doc.Get("Podnaslov");
                //row["Broj.Razgovora"] = doc.Get("Broj.Razgovora");
                //rowPitanja["sample"] = sample;

                ResultsPitanja.Rows.Add(rowPitanja);
            }
            searcher.Dispose();
            return ResultsPitanja;
        }