lucene Term查询

查询demo

		Path path = Paths.get(util.Directory.GetAppPath("indexDir"));
		IndexReader reader = DirectoryReader.open(FSDirectory.open(path));
		//获取IndexSearcher对象
		IndexSearcher indexSearcher = new IndexSearcher(reader);
		Query query = new TermQuery(new Term("title", "国"));
		//查询数据
		TopDocs topDocs = indexSearcher.search(query, 10);
		ScoreDoc[] docs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : docs) {
			Document res = indexSearcher.doc(scoreDoc.doc);
			System.out.println(res.get("title"));
		}

容易犯错警告!!!

在构造Term对象容易大意写成如下

Query query = new Term("国");

则此时利用Term查询不出来结果,因为此时“国”被当做成一个域,并没有检索内容。

切记:利用lucene Term查询一定要记得将域加上去,用来标识搜索词所在的字段名称!!!

Query query = new TermQuery(new Term("title", "国"));

Term类说明文档

介绍:Term术语表示文本中的单词。这是搜索单位。它由两个元素组成,一个字符串形式的单词文本,另一个文本所在字段的名称。请注意,术语可能表示的不仅仅是文本字段中的单词,还包括日期、电子邮件地址、url等。

构造方法:

Term(String fld) fld为域,传入值为空
Term(String fld, BytesRef bytes) fld为域,值为字节流类型
Term(String fld, BytesRefBuilder bytesBuilder) fld为域,值为BytesRefBuilder类型
Term(String fld, String text) fld为域,值为String类型(最常用)

Term方法:

  • field

    public final String field()

    Returns the field of this term. The field indicates the part of a document which this term came from.

  • text

    public final String text()

    Returns the text of this term. In the case of words, this is simply the text of the word. In the case of dates and other types, this is an encoding of the object as a string.

  • toString

    public static final String toString(BytesRef termText)

    Returns human-readable form of the term text. If the term is not unicode, the raw bytes will be printed instead.

  • bytes

    public final BytesRef bytes()

    Returns the bytes of this term, these should not be modified.

  • equals

    public boolean equals(Object obj)

    Overrides:

    equals in class Object

  • hashCode

    public int hashCode()

    Overrides:

    hashCode in class Object

  • compareTo

    public final int compareTo(Term other)

    Compares two terms, returning a negative integer if this term belongs before the argument, zero if this term is equal to the argument, and a positive integer if this term belongs after the argument. The ordering of terms is first by field, then by text.

    Specified by:

    compareTo in interface Comparable

  • toString

    public final String toString()

    Overrides:

    toString in class Object

  • ramBytesUsed

    public long ramBytesUsed()

    Description copied from interface: Accountable

    Return the memory usage of this object in bytes. Negative values are illegal.

说明文档出处:http://lucene.apache.org/core/8_2_0/core/index.html

你可能感兴趣的:(搜索)