Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created July 20, 2012 22:42
Show Gist options
  • Save benfoster/3153711 to your computer and use it in GitHub Desktop.
Save benfoster/3153711 to your computer and use it in GitHub Desktop.
Raven Index with Transform for Oliver
[TestFixture]
public class OliverTest : RavenTest
{
public class OnlineStoreSection
{
public string Id { get; set; }
public TargetAudience TargetAudience { get; set; }
public IEnumerable<string> Tags { get; set; }
}
public class TargetAudience
{
public IEnumerable<string> Sexes { get; set; }
public IEnumerable<int> Ages { get; set; }
}
public class Tag
{
public string Id {get;set;}
public string Title {get;set;}
}
public class StoreSectionIndex : AbstractIndexCreationTask<OnlineStoreSection>
{
public StoreSectionIndex()
{
Map = results => from result in results
select new
{
SectionId = result.Id,
TargetAudience_Sexes = result.TargetAudience.Sexes,
TargetAudience_Ages = result.TargetAudience.Ages,
Tags = result.Tags
};
TransformResults = (store, results) => from result in results
let tags = store.Load<Tag>(result.Tags)
select new
{
SectionId = result.Id,
Sexes = result.TargetAudience.Sexes,
Ages = result.TargetAudience.Ages,
Tags = tags.Select(t => t.Title)
};
}
public class TransformResult
{
public string SectionId { get; set; }
public IEnumerable<string> Sexes { get; set; }
public IEnumerable<int> Ages { get; set; }
public IEnumerable<string> Tags { get; set; }
}
}
[SetUp]
public void Setup()
{
using (var session = Store.OpenSession())
{
var section = new OnlineStoreSection();
section.TargetAudience = new TargetAudience();
section.TargetAudience.Ages = new[] { 1, 2, 3, 4, 5 };
section.TargetAudience.Sexes = new[] { "Male", "Female", "Unsure" };
var tag1 = new Tag { Title = "Foo" };
var tag2 = new Tag { Title = "Bar" };
var tag3 = new Tag { Title = "Day" };
session.Store(tag1);
session.Store(tag2);
session.Store(tag3);
section.Tags = new[] { tag1.Id, tag2.Id, tag3.Id };
session.Store(section);
session.SaveChanges();
}
}
[Test]
public void Can_get_sexes_and_ages_from_section_index()
{
using (var session = Store.OpenSession())
{
var results = session.Query<OnlineStoreSection, StoreSectionIndex>()
.Customize(x => x.WaitForNonStaleResults())
.Where(x => x.TargetAudience.Sexes.Any(s => s == "Male") && !x.TargetAudience.Ages.Any(a => a > 10))
.As<StoreSectionIndex.TransformResult>()
.ToList();
results.ShouldNotBeNull();
results.Count.ShouldEqual(1);
var section = results.First();
section.Sexes.Count().ShouldEqual(3);
section.Ages.Count().ShouldEqual(5);
section.Tags.Count().ShouldEqual(3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment