我正在尝试实现文档索引(大致对应于 DB 行),其中一个字段是整数.我将它们添加到索引中,例如:
I am trying to implement an index of documents (rougly corresponding to DB rows), where one of the fields is an integer. I'm adding them to index like:
Document doc = new Document();
doc.add(new StringField("ticket_number", rs.getString("ticket_number"),
Field.Store.YES));
doc.add(new IntField("ticket_id", rs.getInt("ticket_id"),
Field.Store.YES));
doc.add(new StringField("id_s", rs.getString("ticket_id"),
Field.Store.YES));
w.addDocument(doc);
似乎我根本无法查询 ticket_id 字段,而 id_s 工作正常.
It seems I can't query the ticket_id field at all, while id_s works just fine.
其中一个文件是(为了便于阅读,我添加了空格):
One of the documents is (I added whitespace for readability):
Document<
stored,indexed,tokenized,omitNorms,indexOptions=DOCS_ONLY<ticket_number:230114W>
stored<ticket_id:152>
stored,indexed,tokenized,omitNorms,indexOptions=DOCS_ONLY<id_s:152>>
所以我的 int 字段被存储了,但没有被索引.此查询按预期工作:id_s:152,而此查询从不返回任何内容:ticket_id:152.
So my int field is stored, but not indexed. This query works as expected: id_s:152, while this one never returns anything: ticket_id:152.
我做错了什么?如何将这样的字段添加到索引中并使其可搜索?
What am I doing wrong? How can I add such a field to the index and make it searchable?
以下对我有用:
RAMDirectory idx = new RAMDirectory();
IndexWriter writer = new IndexWriter(
idx,
new IndexWriterConfig(Version.LUCENE_40, new ClassicAnalyzer(Version.LUCENE_40))
);
Document document = new Document();
document.add(new StringField("ticket_number", "t123", Field.Store.YES));
document.add(new IntField("ticket_id", 234, Field.Store.YES));
document.add(new StringField("id_s", "234", Field.Store.YES));
writer.addDocument(document);
writer.commit();
IndexReader reader = DirectoryReader.open(idx);
IndexSearcher searcher = new IndexSearcher(reader);
Query q1 = new TermQuery(new Term("id_s", "234"));
TopDocs td1 = searcher.search(q1, 1);
System.out.println(td1.totalHits); // prints "1"
Query q2 = NumericRangeQuery.newIntRange("ticket_id", 1, 234, 234, true, true);
TopDocs td2 = searcher.search(q2, 1);
System.out.println(td2.totalHits); // prints "1"
正如 femtoRgon 所指出的,对于数值(长整数、日期、浮点数等),您需要具有 NumericRangeQuery 并指定精度.否则 Lucene 不知道你想如何定义相似度.
As femtoRgon pointed out, for numeric values (longs, dates, floats, etc.) you need to have NumericRangeQuery and specify precision. Otherwise Lucene has no idea how do you want to define similarity.
这篇关于如何在 Lucene 4 中搜索 int 字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)