Example #1
0
        /// <summary>
        /// 显示搜索结果
        /// </summary>
        /// <param name="queryResult"></param>
        private void ShowMultFileSearchResult(TopDocs queryResult)
        {
            if (queryResult == null || queryResult.totalHits == 0)
            {
                SetOutput("Sorry,没有搜索到你要的结果。");
                return;
            }
            Searchable[] abs = new Searchable[2];
            abs[0] = new IndexSearcher(INDEX_STORE_PATH);
            abs[1] = new IndexSearcher(INDEX_STORE_PATH1);
            MultiSearcher searcher = new MultiSearcher(abs);//构造MultiSearcher
            int           counter  = 1;

            foreach (ScoreDoc sd in queryResult.scoreDocs)
            {
                try
                {
                    Document doc      = searcher.Doc(sd.doc);
                    string   id       = doc.Get("id");       //获取id
                    string   fileName = doc.Get("filename"); //获取文件名
                    string   contents = doc.Get("contents"); //获取文件内容
                    string   result   = string.Format("这是第{0}个搜索结果,Id为{1},文件名为:{2},文件内容为:{3}{4}", counter, id, fileName, Environment.NewLine, contents);
                    SetOutput(result);
                }
                catch (Exception ex)
                {
                    SetOutput(ex.Message);
                }
                counter++;
            }
        }
Example #2
0
 private void PrintScores(TopDocs docs, int startIndex, int endIndex, MultiSearcher searcher)
 {
     ScoreDoc[] scoreDocs = docs.ScoreDocs;
     for (int i = startIndex; i < endIndex && i < scoreDocs.Count(); i++)
     {
         int      docId = scoreDocs[i].Doc;
         Document doc   = searcher.Doc(docId);
         logger.Info(string.Format("{0}的分值为{1}", doc.Get("productid"), scoreDocs[i].Score));
     }
 }
Example #3
0
        /// <summary>
        /// Perform search
        /// </summary>
        /// <param name="query"></param>
        /// <param name="startIndex"></param>
        /// <param name="blockSize"></param>
        /// <param name="indexDirEs"></param>
        /// <param name="indexDirEn"></param>
        /// <param name="sortBy"></param>
        /// <returns></returns>
        public List <IssueDocument> MedesSearch(Query query, int startIndex, int blockSize, Directory indexDirEs, Directory indexDirEn, Directory indexDirHe, string sortBy)
        {
#if DEBUG
            T.TraceMessage(string.Format("Begin search , query: '{0}'", query.ToString()));
#endif

            List <IssueDocument> result = new List <IssueDocument>();
            try
            {
                // build a multi searcher across the 2 indexes
                MultiSearcher mSearcher = CombineSearchers(indexDirEs, indexDirEn, indexDirHe);

                TopDocs tDocs       = null;
                int     iterateLast = startIndex + blockSize;


                string           customScoreField = "article_id";
                FieldScoreQuery  dateBooster      = new FieldScoreQuery(customScoreField, FieldScoreQuery.Type.FLOAT);
                CustomScoreQuery customQuery      = new CustomScoreQuery(query, dateBooster);

                tDocs = mSearcher.Search(customQuery, 1000);
                //ScoreDoc[] hits = tpDcs.scoreDocs;
                if (startIndex + blockSize > tDocs.TotalHits)
                {
                    iterateLast = tDocs.TotalHits;
                }

                for (int i = startIndex; i < iterateLast; i++)
                {
                    // Document hitDoc = mSearcher.Doc(hits[i].doc);

                    Document hitDoc = mSearcher.Doc(i);

                    result.Add(new IssueDocument()
                    {
                        Id = Int32.Parse(hitDoc.Get("issue_id").ToString())
                    });
                }

                // close the searcher and indexes
                mSearcher.Dispose();
                indexDirEs.Dispose();
                indexDirEn.Dispose();
                indexDirHe.Dispose();
            }
            catch (Exception ex)
            {
                T.TraceError("Error MedesSearch, query '{0}'", query.ToString());
                T.TraceError(ex);
                throw ex;
            }
            return(result);
        }
        /// <summary>
        /// 多索引文件联合查询搜索(带分页)
        /// </summary>
        /// <typeparam name="T">返回结果数据类型</typeparam>
        /// <param name="indexPaths">索引文件路径集合</param>
        /// <param name="query">Query</param>
        /// <param name="sort">排序</param>
        /// <param name="pageIndex">当前搜索页</param>
        /// <param name="pageSize">每页显示数</param>
        /// <param name="count">总搜索结果数</param>
        /// <returns></returns>
        public static List <T> Search <T>(string[] indexPaths, Query query, Sort sort, int pageIndex, int pageSize, out int count) where T : BaseIndexModel
        {
            count = 0;

            if (null == query)
            {
                return(null);
            }

            if (pageIndex < 1)
            {
                pageIndex = 1;
            }

            if (pageSize < 1)
            {
                pageSize = 1;
            }

            //起始搜索位置
            int start = (pageIndex - 1) * pageSize;

            if (null == indexPaths || indexPaths.Length < 1)
            {
                return(null);
            }

            List <IndexSearcher> searchers = new List <IndexSearcher>();

            foreach (var indexPath in indexPaths)
            {
                if (string.IsNullOrWhiteSpace(indexPath))
                {
                    continue;
                }

                //打开索引文件
                FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());

                if (null == directory)
                {
                    continue;
                }

                //检测索引文件是否存在
                bool isExist = IndexReader.IndexExists(directory);

                if (!isExist)
                {
                    continue;
                }

                //创建一个只读的索引文件读取实例
                IndexReader reader = IndexReader.Open(directory, true);

                //实例化IndexSearcher搜索器
                IndexSearcher searcher = new IndexSearcher(reader);

                searchers.Add(searcher);
            }

            if (searchers.Count < 1)
            {
                return(null);
            }

            MultiSearcher multiSearcher = new MultiSearcher(searchers.ToArray());

            //Collector
            TopFieldCollector results = TopFieldCollector.Create(sort, start + pageSize, false, false, false, false);

            //搜索
            multiSearcher.Search(query, results);

            //总命中率(精算)
            count = results.TotalHits;

            //获取当前页文档
            var docs = results.TopDocs(start, pageSize).ScoreDocs;

            //定义一个结果返回变量
            List <T> list = new List <T>();

            //遍历当前页文档,并转换为需要的结果类型
            foreach (var scoreDoc in docs)
            {
                Document doc = multiSearcher.Doc(scoreDoc.Doc);

                var data = new IndexFactory(doc).Result as T;

                if (null != data)
                {
                    list.Add(data);
                }
            }

            return(list);
        }
        public AutoCompletionResult Autocomplete(string text, bool includeExplanation = false)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(AutoCompletionResult.NoResult(text));
            }

            var searchers = _directoryFactory.GetAllDirectories().Select(d =>
            {
                try
                {
                    return(new IndexSearcher(d, true));
                }
                catch (Exception e)
                {
                    _log.Error(e, "While searching directory {0}", d);
                    return(null);
                }
            })
                            .Where(s => s != null)
                            .ToArray();

            using (var searcher = new MultiSearcher(searchers))
            {
                try
                {
                    BooleanQuery query = GetQueryForText(text);

                    var results  = searcher.Search(query, 10);
                    var commands = results.ScoreDocs
                                   .Select(d =>
                    {
                        var document = searcher.Doc(d.Doc);
                        try
                        {
                            Explanation explanation = null;
                            if (includeExplanation)
                            {
                                explanation = searcher.Explain(query, d.Doc);
                            }
                            var coreDoc = CoreDocument.Rehydrate(document);
                            var command = _converterRepository.FromDocumentToItem(coreDoc);

                            return(new AutoCompletionResult.CommandResult(command, coreDoc.GetDocumentId(), explanation));
                        }
                        catch (Exception e)
                        {
                            _log.Error(e, "Error getting command result for document {0}:{1}",
                                       document.GetField(SpecialFields.ConverterId).StringValue,
                                       document.GetField(SpecialFields.Id).StringValue);
                            return(null);
                        }
                    })
                                   .Where(r => r != null);
                    return(AutoCompletionResult.OrderedResult(text, commands));
                }
                catch (ParseException e)
                {
                    _log.Error(e, "Error parsing '{0}'", text);
                    return(AutoCompletionResult.NoResult(text));
                }
            }
        }
Example #6
0
        public void TestMultiSearcher()
        {
            // setup index 1
            RAMDirectory ramDir1 = new RAMDirectory();
            IndexWriter writer1 = new IndexWriter(ramDir1, new StandardAnalyzer(TEST_VERSION), true,
                                                  IndexWriter.MaxFieldLength.UNLIMITED);
            Document d = new Document();
            Field f = new Field(FIELD_NAME, "multiOne", Field.Store.YES, Field.Index.ANALYZED);
            d.Add(f);
            writer1.AddDocument(d);
            writer1.Optimize();
            writer1.Close();
            IndexReader reader1 = IndexReader.Open(ramDir1, true);

            // setup index 2
            RAMDirectory ramDir2 = new RAMDirectory();
            IndexWriter writer2 = new IndexWriter(ramDir2, new StandardAnalyzer(TEST_VERSION), true,
                                                  IndexWriter.MaxFieldLength.UNLIMITED);
            d = new Document();
            f = new Field(FIELD_NAME, "multiTwo", Field.Store.YES, Field.Index.ANALYZED);
            d.Add(f);
            writer2.AddDocument(d);
            writer2.Optimize();
            writer2.Close();
            IndexReader reader2 = IndexReader.Open(ramDir2, true);

            var searchers = new IndexSearcher[2];
            searchers[0] = new IndexSearcher(ramDir1, true);
            searchers[1] = new IndexSearcher(ramDir2, true);
            MultiSearcher multiSearcher = new MultiSearcher(searchers);
            QueryParser parser = new QueryParser(TEST_VERSION, FIELD_NAME, new StandardAnalyzer(TEST_VERSION));
            parser.MultiTermRewriteMethod = MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE;
            query = parser.Parse("multi*");
            Console.WriteLine("Searching for: " + query.ToString(FIELD_NAME));
            // at this point the multisearcher calls combine(query[])
            hits = multiSearcher.Search(query, null, 1000);

            // query = QueryParser.Parse("multi*", FIELD_NAME, new StandardAnalyzer(TEST_VERSION));
            Query[] expandedQueries = new Query[2];
            expandedQueries[0] = query.Rewrite(reader1);
            expandedQueries[1] = query.Rewrite(reader2);
            query = query.Combine(expandedQueries);

            // create an instance of the highlighter with the tags used to surround
            // highlighted text
            Highlighter highlighter = new Highlighter(this, new QueryTermScorer(query));

            for (int i = 0; i < hits.TotalHits; i++)
            {
                String text = multiSearcher.Doc(hits.ScoreDocs[i].Doc).Get(FIELD_NAME);
                TokenStream tokenStream = analyzer.TokenStream(FIELD_NAME, new StringReader(text));
                String highlightedText = highlighter.GetBestFragment(tokenStream, text);
                Console.WriteLine(highlightedText);
            }
            Assert.IsTrue(numHighlights == 2, "Failed to find correct number of highlights " + numHighlights + " found");

        }