Lucene-2.0学习文档(4)

接http://www.iteye.com/topic/39876
下面是搜索的例子:
[code]
public void SearchSort1() throws IOException, ParseException
{
        IndexSearcher indexSearcher = new IndexSearcher("C:\\indexStore");
        QueryParser queryParser = new QueryParser("sort",new StandardAnalyzer());
        Query query = queryParser.parse("4");
       
        Hits hits = indexSearcher.search(query);
        System.out.println("有"+hits.length()+"个结果");
        Document doc = hits.doc(0);
        System.out.println(doc.get("sort"));
}
public void SearchSort2() throws IOException, ParseException
{
        IndexSearcher indexSearcher = new IndexSearcher("C:\\indexStore");
        Query query = new RangeQuery(new Term("sort","1"),new Term("sort","9"),true);//这个地方前面没有提到,它是用于范围的Query可以看一下帮助文档.
        Hits hits = indexSearcher.search(query,new Sort(new SortField("sort",new MySortComparatorSource())));
        System.out.println("有"+hits.length()+"个结果");
        for(int i=0;i
        {
            Document doc = hits.doc(i);
            System.out.println(doc.get("sort"));
        }
}
public class MyScoreDocComparator implements ScoreDocComparator
{
    private Integer[]sort;
    public MyScoreDocComparator(String s,IndexReader reader, String fieldname) throws IOException
    {
        sort = new Integer[reader.maxDoc()];
        for(int i = 0;i
        {
            Document doc =reader.document(i);
            sort[i]=new Integer(doc.get("sort"));
        }
    }
    public int compare(ScoreDoc i, ScoreDoc j)
    {
        if(sort[i.doc]>sort[j.doc])
            return 1;
        if(sort[i.doc]<sort[j.doc])
            return -1;
        return 0;
    }
    public int sortType()
    {
        return SortField.INT;
    }
    public Comparable sortValue(ScoreDoc i)
    {
        // TODO 自动生成方法存根
        return new Integer(sort[i.doc]);
    }
}
public class MySortComparatorSource implements SortComparatorSource
{
    private static final long serialVersionUID = -9189690812107968361L;
    public ScoreDocComparator newComparator(IndexReader reader, String fieldname)
            throws IOException
    {
        if(fieldname.equals("sort"))
            return new MyScoreDocComparator("sort",reader,fieldname);
        return null;
    }
}[/code]
SearchSort1()输出的结果没有排序,SearchSort2()就排序了。
2.多域搜索MultiFieldQueryParser
如果想输入关键字而不想关心是在哪个Field里的就可以用MultiFieldQueryParser了
用它的构造函数即可后面的和一个Field一样。
MultiFieldQueryParser. parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer)                                          ~~~~~~~~~~~~~~~~~
第三个参数比较特殊这里也是与以前lucene1.4.3不一样的地方
看一个例子就知道了
String[] fields = {"filename", "contents", "description"};
 BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
                BooleanClause.Occur.MUST,//在这个Field里必须出现的
                BooleanClause.Occur.MUST_NOT};//在这个Field里不能出现
 MultiFieldQueryParser.parse("query", fields, flags, analyzer);
 (未完)

你可能感兴趣的:(C++,c,搜索引擎,C#,Lucene)