原文出处:http://blog.chenlb.com/2009/11/lucene-2-9-numeric-range-query-powerful.html
Lucene 2.9 对数值类的字段,用 NumericRangeQuery 查询,性能好。它不是把数字简单地用 toString() 做索引的,而是对数值进行 byte 转换,以至可以快速地比较,同时因为字节一样,也方便 Range 查询。
现来测试下,比普通 RangeQuery 查询的性能。分别生成 500W 的数值和字符字段索引(就用 1 - 500W 的数字)。
然后再 400W 到 500W 中(是6位数),按 range 范围 200 查找。
#400W - 500W localhost env
numeric range total = 74781ms, avg = 1495.62ms
range total = 721878ms, avg = 14437.56ms
性能有相差 10 倍左右。
然后再 40W 到 50W 中(是5位数),按 range 范围 200 查找
#40 - 50W localhost env
numeric range total = 8657ms, avg = 173.14ms
range total = 47455ms, avg = 949.1ms
相差也大。
数字的位数越少,相差可能越小。
注意:要使用 NumericRangeQuery ,索引字段必须是 NumbericField。索引代码如:
- for(int i=1; i<5000000; i++) {
- Document doc = new Document();
- doc.add(new NumericField("num", Field.Store.YES, true).setIntValue(i));
- doc.add(new Field("id", ""+i, Field.Store.YES, Field.Index.ANALYZED));
- writer.addDocument(doc);
- }
搜索代码:
- Query q = NumericRangeQuery.newIntRange("num", j, j+200, true, false);
- long s = System.currentTimeMillis();
- searcher.search(q, 200);
- long e = System.currentTimeMillis();
值得一用。
我测试用的源码:lucene-2.9-Test-Numberic-Range