Skip to content

Instantly share code, notes, and snippets.

@blair55
Last active December 11, 2015 09:49
Show Gist options
  • Save blair55/4582709 to your computer and use it in GitHub Desktop.
Save blair55/4582709 to your computer and use it in GitHub Desktop.
A RavenDB MultiMap Index to query across documents on non-id key.
AddMap<Pixel>(pixels =>
from p in pixels
from tag in (p.Tags == null || !p.Tags.Any())
? new[] {"_notags_"}
: p.Tags
select new GroupedResult
{
Tag = tag,
PixelIds = new[] {p.Id},
Urls = new[] {(string) null}
});
AddMap<UrlTagsContainer>(urlTagsContainers =>
from u in urlTagsContainers
from tag in u.Tags
select new GroupedResult
{
Tag = tag,
PixelIds = new string[0],
Urls = new[] {u.Url},
});
public class PixelSearchIndex : AbstractMultiMapIndexCreationTask<PixelSearchIndex.GroupedResult>
{
public class GroupedResult
{
public string Tag { get; set; }
public IEnumerable<string> PixelIds { get; set; }
public IEnumerable<string> Urls { get; set; }
}
public PixelClientSearchIndex()
{
AddMap<Pixel>(pixels => from p in pixels
from tag in (p.Tags == null || !p.Tags.Any()) ? new[] {"_notags_"} : p.Tags
select new GroupedResult
{
Tag = tag,
PixelIds = new[] {p.Id},
Urls = new[] {(string) null}
});
AddMap<UrlTagsContainer>(urlTagsContainers => from u in urlTagsContainers
from tag in u.Tags
select new GroupedResult
{
Tag = tag,
PixelIds = new string[0],
Urls = new[] {u.Url},
});
Reduce = results => from result in results
group result by result.Tag
into g
select new GroupedResult
{
Tag = g.Key,
PixelIds = g.SelectMany(x => x.PixelIds),
Urls = g.SelectMany(x => x.Urls)
};
TransformResults = (database, groupedResults) => from result in groupedResults
from pixelId in result.PixelIds.Distinct()
select new
{
Pixel = database.Load<Pixel>(pixelId),
Urls = result.Urls.Distinct()
};
}
}
Reduce = results =>
from result in results
group result by result.Tag
into g
select new GroupedResult
{
Tag = g.Key,
PixelIds = g.SelectMany(x => x.PixelIds),
Urls = g.SelectMany(x => x.Urls)
};
TransformResults = (database, groupedResults) =>
from result in groupedResults
from pixelId in result.PixelIds.Distinct()
select new
{
Pixel = database.Load<Pixel>(pixelId),
Urls = result.Urls.Distinct()
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment