Skip to content

Instantly share code, notes, and snippets.

@milutinovici
Last active December 11, 2015 13:29
Show Gist options
  • Save milutinovici/4608110 to your computer and use it in GitHub Desktop.
Save milutinovici/4608110 to your computer and use it in GitHub Desktop.
RavenDB generic static index
public class Offer<TProduct> : where TProduct : Product
{
public string Id { get; set; }
public User Seller { get; set; }
public TProduct Product { get; set; }
public decimal Price { get; set; }
}
public class Product
{
public string Id { get; set; }
public string Manufacturer { get; set; }
public string Name { get; set; }
}
public class ProductA : Product
{
public string AProperty { get; set; }
}
public class ProductB : Product
{
public string BProperty { get; set; }
}
public class BestOffersIndex<TProduct> : AbstractIndexCreationTask<Offer<TProduct>, Offer<TProduct>> where TProduct : Product
{
public override string IndexName
{
get
{
var t = GetType();
return t.Name.Replace("`1", "") + "Of" + t.GenericTypeArguments.First().Name;
}
}
public BestOffersIndex()
{
Map = offers => offers
.Select(offer => new
{
Product = offer.Product,
Price = offer.Price,
_ = AsDocument(offer.Product).Select(x => CreateField(x.Key, x.Value))
});
Reduce = results => results.GroupBy(x => x.Product.Id)
.Select(x => new
{
Product = x.First().Product,
Price = x.Min(y => y.Price),
_ = AsDocument(x.First().Product).Select(y => CreateField(y.Key, y.Value))
});
}
}
[TestClass]
public class RavenTest
{
public IDocumentStore Store;
public ProductA PA { get; set; }
public ProductB PB { get; set; }
public RavenTest()
{
PA = new ProductA { AProperty = "A", Manufacturer = "ManufacturerA" };
PB = new ProductB { BProperty = "B", Manufacturer = "ManufacturerB" };
Store = new EmbeddableDocumentStore { RunInMemory = true };
Store.Initialize();
Store.ExecuteIndex(new BestOffersIndex<ProductA>());
Store.ExecuteIndex(new BestOffersIndex<ProductB>());
}
[TestMethod]
public void TestMethod1()
{
using (var session = Store.OpenSession())
{
session.Store(PA);
session.Store(PB);
var o1 = new Offer<ProductA> { Product = PA, Price = 100 };
var o2 = new Offer<ProductB> { Product = PB, Price = 150 };
session.Store(o1);
session.Store(o2);
session.SaveChanges();
}
using (var session = Store.OpenSession())
{
var paOffers = session.Query<Offer<ProductA>, BestOffersIndex<ProductA>>().Customize(x => x.WaitForNonStaleResults()).Where(x => x.Product.AProperty != "").ToList();
Assert.IsTrue(paOffers.Any());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment