2014-01-22 89 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

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