2017-08-19 107 views
1

我使用Lucene.Net版本3.0.3.0,並試圖找到一種方法來搜索數(整數),並最終取回結果在最近的數更高的分數在列表中。Lucene的:查找最近數

爲了簡單起見,我已經簡化了文件:

private void WriteDocument(IndexWriter writer, string product, int weight) 
{ 
    Document document = new Document(); 

    var fieldProduct = new Field("Product", product, Field.Store.YES, Field.Index.NOT_ANALYZED); 
    document.Add(fieldProduct); 

    var fieldWeight = new NumericField("Weight", Field.Store.YES, true); 
    fieldWeight.SetIntValue(weight); 
    document.Add(fieldWeight); 

    writer.AddDocument(document); 
} 

它包括2場:產品重量。最後一個是數字字段。

出於測試目的,我插了一堆文件:

WriteDocument(writer, "ONORNN", 100); 
WriteDocument(writer, "ONORNN", 200); 
WriteDocument(writer, "ONORNN", 300); 
WriteDocument(writer, "ONORAA", 400); 

前3都得到了相同的產品代碼。重量可以是1到999之間的任何值。

我可以看到Lucene.Net提供了一種使用NumericRangeQuery來搜索範圍內的數字的方法,但這並不能幫助我,因爲它不允許輸入接近值,只有mixmax

var weightRange = NumericRangeQuery.NewIntRange("Weight", 1, 999, true, true); 

是否有任何其他類型的查詢,我可以用它來實現我所期待的?

回答

1

我不是C#專家,不幸的是,我趕緊通過什麼可在Lucene.Net 3.0.3,這裏是建議的解決方案看(我將在Java代碼中混合,但希望你能理解)

所以,你需要使用FunctionQuery這是不實際的Lucene 3.0.3的一部分,但它被移植爲Lucene.Net。此查詢將允許根據文檔字段中的值提供自定義評分。

Query q = new FunctionQuery(new DistanceDualFloatFunction(new IntFieldSource("weight"), new ConstValueSource(245))); 

static class DistanceDualFloatFunction extends DualFloatFunction { 

    public DistanceDualFloatFunction(ValueSource a, ValueSource b) { 
     super(a, b); 
    } 

    @Override 
    protected String name() { 
     return "distance function"; 
    } 

    @Override 
    protected float func(int doc, FunctionValues aVals, FunctionValues bVals) { 
     return 1000 - Math.abs(aVals.intVal(doc) - bVals.intVal(doc)); 
    } 
    } 

所以,基本上我創建一個查詢功能,它使用兩個參數的功能,準確地計算(我選擇的值)和實際值之間的絕對差。

我有下列文件:

addDocument(writer, "doc1", 100); 
addDocument(writer, "doc2", 200); 
addDocument(writer, "doc3", 300); 
addDocument(writer, "doc4", 400); 
addDocument(writer, "doc5", 500); 
addDocument(writer, "doc6", 600); 

,結果如下:

stored,indexed,tokenized<title:doc2> 955.0 
stored,indexed,tokenized<title:doc3> 945.0 
stored,indexed,tokenized<title:doc1> 855.0 
stored,indexed,tokenized<title:doc4> 845.0 
stored,indexed,tokenized<title:doc5> 745.0 
stored,indexed,tokenized<title:doc6> 645.0 

的問題,你要臉:

  • 沒有DualFloatFunction是Lucene的。淨,所以你將需要以某種方式使用你有什麼already。最看好我的那個是ReciprocalFloatFunction。另一種方法是實現你自己的DualFloatFunction。

總體結論 - 這是可能的,但你將需要花一些時間採用它到C#和Lucene.Net。

溶液的完整源位於here

+0

太好了。非常感謝你。明天我會給它一個回去,並回來一些反饋。乾杯。 – LeftyX

+0

不客氣。不幸的是,你仍然需要做些什麼 – Mysterion

+0

儘管這似乎是可行的。非常感謝你。 – LeftyX