示例#1
0
        public virtual void  TestBoostsSimple()
        {
            IDictionary <string, float> boosts = new Dictionary <string, float>();

            boosts["b"] = (float)5;
            boosts["t"] = (float)10;
            string[] fields            = new string[] { "b", "t" };
            MultiFieldQueryParser mfqp = new MultiFieldQueryParser(Util.Version.LUCENE_CURRENT, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT), boosts);


            //Check for simple
            Query q = mfqp.Parse("one");

            Assert.AreEqual("b:one^5.0 t:one^10.0", q.ToString());

            //Check for AND
            q = mfqp.Parse("one AND two");
            Assert.AreEqual("+(b:one^5.0 t:one^10.0) +(b:two^5.0 t:two^10.0)", q.ToString());

            //Check for OR
            q = mfqp.Parse("one OR two");
            Assert.AreEqual("(b:one^5.0 t:one^10.0) (b:two^5.0 t:two^10.0)", q.ToString());

            //Check for AND and a field
            q = mfqp.Parse("one AND two AND foo:test");
            Assert.AreEqual("+(b:one^5.0 t:one^10.0) +(b:two^5.0 t:two^10.0) +foo:test", q.ToString());

            q = mfqp.Parse("one^3 AND two^4");
            Assert.AreEqual("+((b:one^5.0 t:one^10.0)^3.0) +((b:two^5.0 t:two^10.0)^4.0)", q.ToString());
        }
        public virtual void  TestStaticMethod2Old()
        {
            System.String[] fields = new System.String[] { "b", "t" };
            //int[] flags = {MultiFieldQueryParser.REQUIRED_FIELD, MultiFieldQueryParser.PROHIBITED_FIELD};
            BooleanClause.Occur[] flags  = new BooleanClause.Occur[] { BooleanClause.Occur.MUST, BooleanClause.Occur.MUST_NOT };
            MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());

            Query q = MultiFieldQueryParser.Parse("one", fields, flags, new StandardAnalyzer());             //, fields, flags, new StandardAnalyzer());

            Assert.AreEqual("+b:one -t:one", q.ToString());

            q = MultiFieldQueryParser.Parse("one two", fields, flags, new StandardAnalyzer());
            Assert.AreEqual("+(b:one b:two) -(t:one t:two)", q.ToString());

            try
            {
                BooleanClause.Occur[] flags2 = new BooleanClause.Occur[] { BooleanClause.Occur.MUST };
                q = MultiFieldQueryParser.Parse("blah", fields, flags2, new StandardAnalyzer());
                Assert.Fail();
            }
            catch (System.ArgumentException e)
            {
                // expected exception, array length differs
            }
        }
        public virtual void  TestBoostsSimple()
        {
            System.Collections.IDictionary boosts = new System.Collections.Hashtable();
            boosts["b"] = (float)5;
            boosts["t"] = (float)10;
            System.String[]       fields = new System.String[] { "b", "t" };
            MultiFieldQueryParser mfqp   = new MultiFieldQueryParser(fields, new StandardAnalyzer(), boosts);


            //Check for simple
            Query q = mfqp.Parse("one");

            Assert.AreEqual("b:one^5.0 t:one^10.0", q.ToString());

            //Check for AND
            q = mfqp.Parse("one AND two");
            Assert.AreEqual("+(b:one^5.0 t:one^10.0) +(b:two^5.0 t:two^10.0)", q.ToString());

            //Check for OR
            q = mfqp.Parse("one OR two");
            Assert.AreEqual("(b:one^5.0 t:one^10.0) (b:two^5.0 t:two^10.0)", q.ToString());

            //Check for AND and a field
            q = mfqp.Parse("one AND two AND foo:test");
            Assert.AreEqual("+(b:one^5.0 t:one^10.0) +(b:two^5.0 t:two^10.0) +foo:test", q.ToString());

            q = mfqp.Parse("one^3 AND two^4");
            Assert.AreEqual("+((b:one^5.0 t:one^10.0)^3.0) +((b:two^5.0 t:two^10.0)^4.0)", q.ToString());
        }
示例#4
0
        // verify parsing of query using a stopping analyzer
        private void  AssertStopQueryEquals(string qtxt, string expectedRes)
        {
            string[] fields = new string[] { "b", "t" };
            Occur[]  occur  = new Occur[] { Occur.SHOULD, Occur.SHOULD };
            TestQueryParser.QPTestAnalyzer a    = new TestQueryParser.QPTestAnalyzer();
            MultiFieldQueryParser          mfqp = new MultiFieldQueryParser(Util.Version.LUCENE_CURRENT, fields, a);

            Query q = mfqp.Parse(qtxt);

            Assert.AreEqual(expectedRes, q.ToString());

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, qtxt, fields, occur, a);
            Assert.AreEqual(expectedRes, q.ToString());
        }
        // verify parsing of query using a stopping analyzer
        private void  AssertStopQueryEquals(System.String qtxt, System.String expectedRes)
        {
            System.String[] fields              = new System.String[] { "b", "t" };
            Occur[]         occur               = new Occur[] { Occur.SHOULD, Occur.SHOULD };
            TestQueryParser.QPTestAnalyzer a    = new TestQueryParser.QPTestAnalyzer();
            MultiFieldQueryParser          mfqp = new MultiFieldQueryParser(fields, a);

            Query q = mfqp.Parse(qtxt);

            Assert.AreEqual(expectedRes, q.ToString());

            q = MultiFieldQueryParser.Parse(qtxt, fields, occur, a);
            Assert.AreEqual(expectedRes, q.ToString());
        }
        public virtual void  TestAnalyzerReturningNull()
        {
            System.String[]       fields = new System.String[] { "f1", "f2", "f3" };
            MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new AnalyzerReturningNull());
            Query q = parser.Parse("bla AND blo");

            Assert.AreEqual("+(f2:bla f3:bla) +(f2:blo f3:blo)", q.ToString());
            // the following queries are not affected as their terms are not analyzed anyway:
            q = parser.Parse("bla*");
            Assert.AreEqual("f1:bla* f2:bla* f3:bla*", q.ToString());
            q = parser.Parse("bla~");
            Assert.AreEqual("f1:bla~0.5 f2:bla~0.5 f3:bla~0.5", q.ToString());
            q = parser.Parse("[a TO c]");
            Assert.AreEqual("f1:[a TO c] f2:[a TO c] f3:[a TO c]", q.ToString());
        }
示例#7
0
        public virtual void  TestStaticMethod2()
        {
            string[] fields = new [] { "b", "t" };
            Occur[]  flags  = new [] { Occur.MUST, Occur.MUST_NOT };
            Query    q      = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "one", fields, flags, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));

            Assert.AreEqual("+b:one -t:one", q.ToString());

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "one two", fields, flags, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));
            Assert.AreEqual("+(b:one b:two) -(t:one t:two)", q.ToString());

            Occur[] flags2 = new [] { Occur.MUST };
            Assert.Throws <ArgumentException>(
                () =>
                MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "blah", fields, flags2,
                                            new StandardAnalyzer(Util.Version.LUCENE_CURRENT)));
        }
示例#8
0
        public virtual void  AssertQueryEqualsDOA(System.String query, Analyzer a, System.String result)
        {
            Query q = GetQueryDOA(query, a);

            System.String s = q.ToString("Field");
            if (!s.Equals(result))
            {
                Assert.Fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result + "/");
            }
        }
示例#9
0
        public virtual void  TestStaticMethod2Old()
        {
            var fields = new[] { "b", "t" };
            //int[] flags = {MultiFieldQueryParser.REQUIRED_FIELD, MultiFieldQueryParser.PROHIBITED_FIELD};
            var flags  = new[] { Occur.MUST, Occur.MUST_NOT };
            var parser = new MultiFieldQueryParser(Util.Version.LUCENE_CURRENT, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));

            Query q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "one", fields, flags, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));             //, fields, flags, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));

            Assert.AreEqual("+b:one -t:one", q.ToString());

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "one two", fields, flags, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));
            Assert.AreEqual("+(b:one b:two) -(t:one t:two)", q.ToString());

            var flags2 = new [] { Occur.MUST };

            Assert.Throws <ArgumentException>(
                () =>
                MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, "blah", fields, flags2,
                                            new StandardAnalyzer(Util.Version.LUCENE_CURRENT)));
        }
示例#10
0
 /* (non-Javadoc) @see Lucene.Net.Search.Query#toString(java.lang.String) */
 public override System.String ToString(System.String field)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder(Name()).Append("(");
     sb.Append(subQuery.ToString(field));
     for (int i = 0; i < valSrcQueries.Length; i++)
     {
         sb.Append(", ").Append(valSrcQueries[i].ToString(field));
     }
     sb.Append(")");
     sb.Append(strict ? " STRICT" : "");
     return(sb.ToString() + ToStringUtils.Boost(GetBoost()));
 }
示例#11
0
        public virtual void  AssertWildcardQueryEquals(System.String query, bool lowercase, System.String result)
        {
            QueryParsers.QueryParser qp = GetParser(null);
            qp.SetLowercaseWildcardTerms(lowercase);
            Query q = qp.Parse(query);

            System.String s = q.ToString("Field");
            if (!s.Equals(result))
            {
                Assert.Fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /" + result + "/");
            }
        }
示例#12
0
        public virtual void  TestPerFieldAnalyzer()
        {
            PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new SimpleAnalyzer());

            analyzer.AddAnalyzer("partnum", new KeywordAnalyzer());

            QueryParser queryParser = new QueryParser(Version.LUCENE_CURRENT, "description", analyzer);
            Query       query       = queryParser.Parse("partnum:Q36 AND SPACE");

            ScoreDoc[] hits = searcher.Search(query, null, 1000, null).ScoreDocs;
            Assert.AreEqual("+partnum:Q36 +space", query.ToString("description"), "Q36 kept as-is");
            Assert.AreEqual(1, hits.Length, "doc found!");
        }
        public virtual void  TestStaticMethod3Old()
        {
            System.String[]       queries = new System.String[] { "one", "two" };
            System.String[]       fields  = new System.String[] { "b", "t" };
            BooleanClause.Occur[] flags   = new BooleanClause.Occur[] { BooleanClause.Occur.MUST, BooleanClause.Occur.MUST_NOT };
            Query q = MultiFieldQueryParser.Parse(queries, fields, flags, new StandardAnalyzer());

            Assert.AreEqual("+b:one -t:two", q.ToString());

            try
            {
                BooleanClause.Occur[] flags2 = new BooleanClause.Occur[] { BooleanClause.Occur.MUST };
                q = MultiFieldQueryParser.Parse(queries, fields, flags2, new StandardAnalyzer());
                Assert.Fail();
            }
            catch (System.ArgumentException e)
            {
                // expected exception, array length differs
            }
        }
        public virtual void  TestStaticMethod1()
        {
            System.String[] fields  = new System.String[] { "b", "t" };
            System.String[] queries = new System.String[] { "one", "two" };
            Query           q       = MultiFieldQueryParser.Parse(queries, fields, new StandardAnalyzer());

            Assert.AreEqual("b:one t:two", q.ToString());

            System.String[] queries2 = new System.String[] { "+one", "+two" };
            q = MultiFieldQueryParser.Parse(queries2, fields, new StandardAnalyzer());
            Assert.AreEqual("(+b:one) (+t:two)", q.ToString());

            System.String[] queries3 = new System.String[] { "one", "+two" };
            q = MultiFieldQueryParser.Parse(queries3, fields, new StandardAnalyzer());
            Assert.AreEqual("b:one (+t:two)", q.ToString());

            System.String[] queries4 = new System.String[] { "one +more", "+two" };
            q = MultiFieldQueryParser.Parse(queries4, fields, new StandardAnalyzer());
            Assert.AreEqual("(b:one +b:more) (+t:two)", q.ToString());

            System.String[] queries5 = new System.String[] { "blah" };
            try
            {
                q = MultiFieldQueryParser.Parse(queries5, fields, new StandardAnalyzer());
                Assert.Fail();
            }
            catch (System.ArgumentException e)
            {
                // expected exception, array length differs
            }

            // check also with stop words for this static form (qtxts[], fields[]).
            TestQueryParser.QPTestAnalyzer stopA = new TestQueryParser.QPTestAnalyzer();

            System.String[] queries6 = new System.String[] { "((+stop))", "+((stop))" };
            q = MultiFieldQueryParser.Parse(queries6, fields, stopA);
            Assert.AreEqual("", q.ToString());

            System.String[] queries7 = new System.String[] { "one ((+stop)) +more", "+((stop)) +two" };
            q = MultiFieldQueryParser.Parse(queries7, fields, stopA);
            Assert.AreEqual("(b:one +b:more) (+t:two)", q.ToString());
        }
示例#15
0
        public virtual void  TestStaticMethod1()
        {
            var   fields  = new [] { "b", "t" };
            var   queries = new [] { "one", "two" };
            Query q       = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));

            Assert.AreEqual("b:one t:two", q.ToString());

            var queries2 = new [] { "+one", "+two" };

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries2, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));
            Assert.AreEqual("(+b:one) (+t:two)", q.ToString());

            var queries3 = new [] { "one", "+two" };

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries3, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));
            Assert.AreEqual("b:one (+t:two)", q.ToString());

            var queries4 = new [] { "one +more", "+two" };

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries4, fields, new StandardAnalyzer(Util.Version.LUCENE_CURRENT));
            Assert.AreEqual("(b:one +b:more) (+t:two)", q.ToString());

            var queries5 = new [] { "blah" };

            Assert.Throws <ArgumentException>(() => MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries5, fields,
                                                                                new StandardAnalyzer(Util.Version.LUCENE_CURRENT)));

            // check also with stop words for this static form (qtxts[], fields[]).
            var stopA = new TestQueryParser.QPTestAnalyzer();

            var queries6 = new [] { "((+stop))", "+((stop))" };

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries6, fields, stopA);
            Assert.AreEqual("", q.ToString());

            var queries7 = new [] { "one ((+stop)) +more", "+((stop)) +two" };

            q = MultiFieldQueryParser.Parse(Util.Version.LUCENE_CURRENT, queries7, fields, stopA);
            Assert.AreEqual("(b:one +b:more) (+t:two)", q.ToString());
        }
 public QueryTraceScopeContext(Lucene.Net.Search.Query query)
 {
     Query = query.ToString();
 }
示例#17
0
        /// <summary>
        /// Deal with the information need as suitable query
        /// search the processed query
        /// display the result
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void submitButton_Click(object sender, EventArgs e)
        {
            CleanResult();
            infoNeed = InfoNeedInput.Text;
            Stopwatch stopwatch = new Stopwatch();

            //give an error warning when input is null
            if (infoNeed == "")
            {
                MessageBox.Show("Invalid input!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                InfoNeedInput.Clear();
                return;
            }



            //take the analyzer selected by users
            string analyzerSelection = comboBox1.SelectedItem.ToString();

            myLuceneApp.AnalyzerSelection(analyzerSelection);

            //make the input "as is" to search
            myLuceneApp.CreateSearcher();
            if (checkBox1.Checked)
            {
                infoNeed = infoNeed.Replace("\"", "");
                infoNeed = "\"" + infoNeed + "\"";
            }

            string expandedQueryItems = "";

            OptionOfQeryExpansionAndWeighterQueries(expandedQueryItems);
            AnalyzerChoice();



            //record searching time
            stopwatch.Start();
            //parse the information need into final query terms
            Lucene.Net.Search.Query query = myLuceneApp.InfoParser(infoNeed);
            string queryText = query.ToString();

            //display the final query in textbox
            textBox2.Text = queryText;
            Lucene.Net.Search.TopDocs result = myLuceneApp.SearchText(query);
            stopwatch.Stop();

            TimeSpan timeSpan = stopwatch.Elapsed;
            double   time     = timeSpan.TotalSeconds;

            time = Math.Round(time, 4);
            toolStripStatusLabel2.Text = "Searching time: " + time.ToString() + "s";
            int rank = 0;


            pageDivded.DtSource.Columns.Add("list");
            //display the number of result
            groupBox5.Text = "Result: " + result.TotalHits.ToString();
            //display the results
            foreach (Lucene.Net.Search.ScoreDoc scoreDoc in result.ScoreDocs)
            {
                rank++;
                Lucene.Net.Documents.Document doc = myLuceneApp.GetSearcher.Doc(scoreDoc.Doc);
                string ID             = "ID" + doc.Get("id").Replace(" ", "").ToString();
                string title          = "Title: " + doc.Get("title").ToString();
                string author         = "Author: " + doc.Get("author").ToString();
                string bbibliographic = "Bibliographic: " + doc.Get("bibliographic").ToString();
                string textAbstract   = doc.Get("firstSentence").ToString();


                string row = "Rank:" + rank + "\r\n" + title + "\r\n" + author + "\r\n" + bbibliographic + "\r\n" + textAbstract + "\r\n";


                pageDivded.DtSource.Rows.Add(row);
            }
            //A prompt message pop up when there is no results
            if (pageDivded.DtSource.Rows.Count <= 0)
            {
                MessageBox.Show("No result", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            pageDivded.DividedPage();
            dataGridView1.DataSource = pageDivded.LoadPage();
            dataGridView1.Columns["list"].FillWeight = 240;
            dataGridView1.Show();
            label6.Text = pageDivded.PageNumber();
            myLuceneApp.CleanUpSearcher();
        }
		public virtual void  DoSearching(Query unReWrittenQuery)
		{
			searcher = new IndexSearcher(ramDir);
			//for any multi-term queries to work (prefix, wildcard, range,fuzzy etc) you must use a rewritten query!
			query = unReWrittenQuery.Rewrite(reader);
			System.Console.Out.WriteLine("Searching for: " + query.ToString(FIELD_NAME));
			hits = searcher.Search(query);
		}
		public virtual void  TestMultiSearcher()
		{
			//setup index 1
			RAMDirectory ramDir1 = new RAMDirectory();
			IndexWriter writer1 = new IndexWriter(ramDir1, new StandardAnalyzer(), true);
			Document d = new Document();
			Field f = new Field(FIELD_NAME, "multiOne", Field.Store.YES, Field.Index.TOKENIZED);
			d.Add(f);
			writer1.AddDocument(d);
			writer1.Optimize();
			writer1.Close();
			IndexReader reader1 = IndexReader.Open(ramDir1);
			
			//setup index 2
			RAMDirectory ramDir2 = new RAMDirectory();
			IndexWriter writer2 = new IndexWriter(ramDir2, new StandardAnalyzer(), true);
			d = new Document();
			f = new Field(FIELD_NAME, "multiTwo", Field.Store.YES, Field.Index.TOKENIZED);
			d.Add(f);
			writer2.AddDocument(d);
			writer2.Optimize();
			writer2.Close();
			IndexReader reader2 = IndexReader.Open(ramDir2);
			
			
			
			IndexSearcher[] searchers = new IndexSearcher[2];
			searchers[0] = new IndexSearcher(ramDir1);
			searchers[1] = new IndexSearcher(ramDir2);
			MultiSearcher multiSearcher = new MultiSearcher(searchers);
			QueryParser parser = new QueryParser(FIELD_NAME, new StandardAnalyzer());
            parser.SetMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
			query = parser.Parse("multi*");
			System.Console.Out.WriteLine("Searching for: " + query.ToString(FIELD_NAME));
			//at this point the multisearcher calls combine(query[])
			hits = multiSearcher.Search(query);
			
			//query = QueryParser.parse("multi*", FIELD_NAME, new StandardAnalyzer());
			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 QueryScorer(query));
			
			for (int i = 0; i < hits.Length(); i++)
			{
				System.String text = hits.Doc(i).Get(FIELD_NAME);
				TokenStream tokenStream = analyzer.TokenStream(FIELD_NAME, new System.IO.StringReader(text));
				System.String highlightedText = highlighter.GetBestFragment(tokenStream, text);
				System.Console.Out.WriteLine(highlightedText);
			}
			Assert.IsTrue(numHighlights == 2, "Failed to find correct number of highlights " + numHighlights + " found");
		}
        public virtual void  TestSimple()
        {
            System.String[]       fields = new System.String[] { "b", "t" };
            MultiFieldQueryParser mfqp   = new MultiFieldQueryParser(fields, new StandardAnalyzer());

            Query q = mfqp.Parse("one");

            Assert.AreEqual("b:one t:one", q.ToString());

            q = mfqp.Parse("one two");
            Assert.AreEqual("(b:one t:one) (b:two t:two)", q.ToString());

            q = mfqp.Parse("+one +two");
            Assert.AreEqual("+(b:one t:one) +(b:two t:two)", q.ToString());

            q = mfqp.Parse("+one -two -three");
            Assert.AreEqual("+(b:one t:one) -(b:two t:two) -(b:three t:three)", q.ToString());

            q = mfqp.Parse("one^2 two");
            Assert.AreEqual("((b:one t:one)^2.0) (b:two t:two)", q.ToString());

            q = mfqp.Parse("one~ two");
            Assert.AreEqual("(b:one~0.5 t:one~0.5) (b:two t:two)", q.ToString());

            q = mfqp.Parse("one~0.8 two^2");
            Assert.AreEqual("(b:one~0.8 t:one~0.8) ((b:two t:two)^2.0)", q.ToString());

            q = mfqp.Parse("one* two*");
            Assert.AreEqual("(b:one* t:one*) (b:two* t:two*)", q.ToString());

            q = mfqp.Parse("[a TO c] two");
            Assert.AreEqual("(b:[a TO c] t:[a TO c]) (b:two t:two)", q.ToString());

            q = mfqp.Parse("w?ldcard");
            Assert.AreEqual("b:w?ldcard t:w?ldcard", q.ToString());

            q = mfqp.Parse("\"foo bar\"");
            Assert.AreEqual("b:\"foo bar\" t:\"foo bar\"", q.ToString());

            q = mfqp.Parse("\"aa bb cc\" \"dd ee\"");
            Assert.AreEqual("(b:\"aa bb cc\" t:\"aa bb cc\") (b:\"dd ee\" t:\"dd ee\")", q.ToString());

            q = mfqp.Parse("\"foo bar\"~4");
            Assert.AreEqual("b:\"foo bar\"~4 t:\"foo bar\"~4", q.ToString());

            // LUCENE-1213: MultiFieldQueryParser was ignoring slop when phrase had a field.
            q = mfqp.Parse("b:\"foo bar\"~4");
            Assert.AreEqual("b:\"foo bar\"~4", q.ToString());

            // make sure that terms which have a field are not touched:
            q = mfqp.Parse("one f:two");
            Assert.AreEqual("(b:one t:one) f:two", q.ToString());

            // AND mode:
            mfqp.SetDefaultOperator(QueryParser.AND_OPERATOR);
            q = mfqp.Parse("one two");
            Assert.AreEqual("+(b:one t:one) +(b:two t:two)", q.ToString());
            q = mfqp.Parse("\"aa bb cc\" \"dd ee\"");
            Assert.AreEqual("+(b:\"aa bb cc\" t:\"aa bb cc\") +(b:\"dd ee\" t:\"dd ee\")", q.ToString());
        }
示例#21
0
        /// <summary>
        /// save result as txt file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveResultButton_Click_2(object sender, EventArgs e)
        {
            //set paramaeter of savefiledialog
            Stream stream;

            saveFileDialog1.CreatePrompt     = true;
            saveFileDialog1.OverwritePrompt  = true;
            saveFileDialog1.DefaultExt       = "txt";
            saveFileDialog1.Filter           = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (infoNeed == "")
            {
                MessageBox.Show("Invalid input!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                InfoNeedInput.Clear();
                return;
            }

            myLuceneApp.CreateSearcher();
            Lucene.Net.Search.Query   query  = myLuceneApp.InfoParser(infoNeed);
            Lucene.Net.Search.TopDocs result = myLuceneApp.SearchText(query);
            string query1      = query.ToString();
            string path        = "";
            string oneLine     = "";
            int    rank        = 0;
            string topicID     = textBox3.Text;
            string gropunumber = "0123456798_0987654321_ourteam";


            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                path = saveFileDialog1.FileName;
                if (File.Exists(path))
                {
                    using (StreamWriter myWritter1 = File.AppendText(path))
                    {
                        foreach (Lucene.Net.Search.ScoreDoc scoreDoc in result.ScoreDocs)
                        {
                            rank++;
                            Lucene.Net.Documents.Document doc = myLuceneApp.GetSearcher.Doc(scoreDoc.Doc);
                            string docID = doc.Get("id").Replace(" ", "").Replace("\n", "").Replace("\r", "").ToString();
                            oneLine = string.Format("{0}\tQ0\t{1}\t{2}\t{3}\t{4}", topicID, docID, rank, scoreDoc.Score.ToString(), gropunumber);
                            myWritter1.WriteLine(oneLine);
                        }
                        myWritter1.Flush();
                        myWritter1.Close();
                    }
                }

                else if ((stream = saveFileDialog1.OpenFile()) != null)
                {
                    using (StreamWriter myWritter2 = new StreamWriter(stream))
                    {
                        foreach (Lucene.Net.Search.ScoreDoc scoreDoc in result.ScoreDocs)
                        {
                            rank++;
                            Lucene.Net.Documents.Document doc = myLuceneApp.GetSearcher.Doc(scoreDoc.Doc);
                            string docID = doc.Get("id").Replace(" ", "").Replace("\n", "").Replace("\r", "").ToString();
                            oneLine = string.Format("{0}\tQ0\t{1}\t{2}\t{3}\t{4}", topicID, docID, rank, scoreDoc.Score.ToString(), gropunumber);
                            myWritter2.WriteLine(oneLine);
                        }
                        myWritter2.Flush();
                        myWritter2.Close();
                        //"{0}\tQ0\t{1,10}\t{2,5}\t{3,15}\t{4,38}"
                    }
                }
            }
        }
示例#22
0
        public static void  Main(System.String[] args)
        {
            System.String usage = "Usage:\t" + typeof(SearchFiles) + "[-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field] [-paging hitsPerPage]";
            usage += "\n\tSpecify 'false' for hitsPerPage to use streaming instead of paging search.";
            if (args.Length > 0 && ("-h".Equals(args[0]) || "-help".Equals(args[0])))
            {
                System.Console.Out.WriteLine(usage);
                System.Environment.Exit(0);
            }

            System.String index   = "index";
            System.String field   = "contents";
            System.String queries = null;
            int           repeat  = 0;
            bool          raw     = false;

            System.String normsField  = null;
            bool          paging      = true;
            int           hitsPerPage = 10;

            for (int i = 0; i < args.Length; i++)
            {
                if ("-index".Equals(args[i]))
                {
                    index = args[i + 1];
                    i++;
                }
                else if ("-field".Equals(args[i]))
                {
                    field = args[i + 1];
                    i++;
                }
                else if ("-queries".Equals(args[i]))
                {
                    queries = args[i + 1];
                    i++;
                }
                else if ("-repeat".Equals(args[i]))
                {
                    repeat = System.Int32.Parse(args[i + 1]);
                    i++;
                }
                else if ("-raw".Equals(args[i]))
                {
                    raw = true;
                }
                else if ("-norms".Equals(args[i]))
                {
                    normsField = args[i + 1];
                    i++;
                }
                else if ("-paging".Equals(args[i]))
                {
                    if (args[i + 1].Equals("false"))
                    {
                        paging = false;
                    }
                    else
                    {
                        hitsPerPage = System.Int32.Parse(args[i + 1]);
                        if (hitsPerPage == 0)
                        {
                            paging = false;
                        }
                    }
                    i++;
                }
            }

            IndexReader reader = IndexReader.Open(FSDirectory.Open(new System.IO.FileInfo(index)), true);             // only searching, so read-only=true

            if (normsField != null)
            {
                reader = new OneNormsReader(reader, normsField);
            }

            Searcher searcher = new IndexSearcher(reader);
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

            System.IO.StreamReader in_Renamed = null;
            if (queries != null)
            {
                in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(queries, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(queries, System.Text.Encoding.Default).CurrentEncoding);
            }
            else
            {
                in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.GetEncoding("UTF-8")).BaseStream, new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.GetEncoding("UTF-8")).CurrentEncoding);
            }
            QueryParser parser = new QueryParser(field, analyzer);

            while (true)
            {
                if (queries == null)
                {
                    // prompt the user
                    System.Console.Out.WriteLine("Enter query: ");
                }

                System.String line = in_Renamed.ReadLine();

                if (line == null || line.Length == -1)
                {
                    break;
                }

                line = line.Trim();
                if (line.Length == 0)
                {
                    break;
                }

                Query query = parser.Parse(line);
                System.Console.Out.WriteLine("Searching for: " + query.ToString(field));


                if (repeat > 0)
                {
                    // repeat & time as benchmark
                    System.DateTime start = System.DateTime.Now;
                    for (int i = 0; i < repeat; i++)
                    {
                        searcher.Search(query, null, 100);
                    }
                    System.DateTime end = System.DateTime.Now;
                    System.Console.Out.WriteLine("Time: " + (end.Millisecond - start.Millisecond) + "ms");
                }

                if (paging)
                {
                    DoPagingSearch(in_Renamed, searcher, query, hitsPerPage, raw, queries == null);
                }
                else
                {
                    DoStreamingSearch(searcher, query);
                }
            }
            reader.Close();
        }
示例#23
0
        public static void  Main(System.String[] args)
        {
            try
            {
                Searcher searcher = new IndexSearcher(@"index");
                Analyzer analyzer = new StandardAnalyzer();

                System.IO.StreamReader in_Renamed = new System.IO.StreamReader(new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(System.Console.OpenStandardInput(), System.Text.Encoding.Default).CurrentEncoding);
                while (true)
                {
                    System.Console.Out.Write("Query: ");
                    System.String line = in_Renamed.ReadLine();

                    if (line.Length == -1)
                    {
                        break;
                    }

                    Query query = QueryParser.Parse(line, "contents", analyzer);
                    System.Console.Out.WriteLine("Searching for: " + query.ToString("contents"));

                    Hits hits = searcher.Search(query);
                    System.Console.Out.WriteLine(hits.Length() + " total matching documents");

                    int HITS_PER_PAGE = 10;
                    for (int start = 0; start < hits.Length(); start += HITS_PER_PAGE)
                    {
                        int end = System.Math.Min(hits.Length(), start + HITS_PER_PAGE);
                        for (int i = start; i < end; i++)
                        {
                            Document      doc  = hits.Doc(i);
                            System.String path = doc.Get("path");
                            if (path != null)
                            {
                                System.Console.Out.WriteLine(i + ". " + path);
                            }
                            else
                            {
                                System.String url = doc.Get("url");
                                if (url != null)
                                {
                                    System.Console.Out.WriteLine(i + ". " + url);
                                    System.Console.Out.WriteLine("   - " + doc.Get("title"));
                                }
                                else
                                {
                                    System.Console.Out.WriteLine(i + ". " + "No path nor URL for this document");
                                }
                            }
                        }

                        if (hits.Length() > end)
                        {
                            System.Console.Out.Write("more (y/n) ? ");
                            line = in_Renamed.ReadLine();
                            if (line.Length == 0 || line[0] == 'n')
                            {
                                break;
                            }
                        }
                    }
                }
                searcher.Close();
            }
            catch (System.Exception e)
            {
                System.Console.Out.WriteLine(" caught a " + e.GetType() + "\n with message: " + e.Message);
            }
        }
示例#24
0
 public override System.String ToString(System.String f)
 {
     return(q.ToString(f));
 }