2014-01-22 50 views
3

我是ElasticSearch的新手,並試圖在我的C#應用​​程序中使用它與巢。我有一個擁有基本類型與類別列表中的類繼承自它:映射到一個多態列表

public class Automobile 
{ 
    public string ModelName { get; set; } 
    public double EngineSize { get; set; } 
} 

public class Truck : Automobile 
{ 
    public double CarryWeight { get; set; } 
} 

public class Car : Automobile 
{ 
    public short SaftyStars { get; set; } 
} 

public class MotorCycle : Automobile 
{ 
    public double DecibleNoise { get; set; } 
} 

public class AutoDealerShip 
{ 
    public string Name { get; set; } 
    [ElasticProperty(Type = FieldType.nested)] 
    public IList<Automobile> Models { get; set; } 

    public AutoDealerShip() 
    { 
     Models = new List<Automobile>(); 
    } 
} 

我試圖映射類,以便實際對象將被保存:

ElasticClient.MapFluent<AutoDealerShip>(m => m.MapFromAttributes(). 
              Properties(prop => prop. 
              NestedObject<Automobile>(n => n. 
               Name(p => p. 
               Models.First()). 
                 MapFromAttributes(). 
                 Dynamic()))); 

當試圖索引數據和檢索:

private static void IndexPolymorphicObject() 
{ 
    ElasticClient.DeleteIndex(PersonIndex); 

    var dealerShip = new AutoDealerShip(); 
    dealerShip.Name = "Mikes dealership"; 
    dealerShip.Models.Add(new Truck()); 
    dealerShip.Models.Add(new Car()); 
    dealerShip.Models.Add(new MotorCycle()); 
    ElasticClient.Index(dealerShip); 
    ElasticClient.Flush(); 
} 

private static void GetPolyMorphicData() 
{ 
    var result = ElasticClient.Search<AutoDealerShip>(srch => srch. 
               Query(q => q.MatchAll())); 
    var dealerShip = result.Documents.First(); 
    foreach (var automobile in dealerShip.Models) 
    { 
     Console.WriteLine("Automobile of type {0}",automobile.GetType()); 
    } 
} 

我不斷收到回型汽車的對象。有沒有辦法使用嵌套存儲多態數據?

感謝,

以斯哈

回答

4

NEST在默認情況下已經爲你存儲

文件的逆變結果,因此,如果你做的大力支持

Index<B>()

Index<C>()

Index<D>()

然後搜索Search<A>(s=>s.Types(B,C,D)),因爲它們都來自A,您將得到一個IEnumerable結果,其中包含B,C和D的實際實例。

要想在你自己的文件中進行對比/協變,你必須自己進行佈線。

您必須在屬性上註冊一個自定義jsonconverter,以確保JSON.net將json反序列化爲實際的子類型而不是晚餐。

+0

感謝您的回覆。這可能是一個愚蠢的問題,但這些是如何做的子對象。我如何索引它們? –

+0

這就是我試圖解釋的,因爲這是您自己的對象內的協方差,您必須編寫自己的序列化程序來編寫自定義Json.net轉換程序來處理屬性的協方差。 –

+0

似乎工作。非常感謝你。 –