Replies: 1 comment 3 replies
-
Indeed, what you need is a map-reduce index. I recommend learning about this type of an index as it's a very powerful tool. public class Users : AbstractIndexCreationTask<User, Users.Result>
{
public class Result
{
public string GroupName { get; set; }
public int Count { get; set; }
}
public Users()
{
Map = users => users.SelectMany(u => u.Groups
.Select(g => new Result
{
GroupName = LoadDocument<Group>(g).Name,
Count = 1
}));
Reduce = results => results.GroupBy(r => r.GroupName)
.Select(g => new Result
{
GroupName = g.Key,
Count = g.Sum(x => x.Count)
});
}
} Here's equivalent of the above if you prefer a query syntax Map = users => from user in users
from groupId in user.Groups
select new Result
{
GroupName = LoadDocument<Group>(groupId).Name,
Count = 1
};
Reduce = results => from result in results
group result by result.GroupName into g
select new Result
{
GroupName = g.Key,
Count = g.Sum(x => x.Count)
}; Then you can query it like so var usersInGroups = session.Query<Users.Result, Users>();
// or
var usersInTest = session.Query<Users.Result, Users>().Where(r => r.GroupName == "test"); Please note that this index loads related documents, which may incur performance overhead in some cases. Nevertheless it is probably the best way if you want to execute the query database-side in one request. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
Scenario: Search groups by group name and display the number of users assigned to each group search result.
Seems trivial but for some reason, I'm stuck generating a proper index for this requirement.
A user can belong to one or more groups. As it’s expected that a user may belong just to a few groups, the User holds an array of group ids.
User:
Requirement: Search for groups by name (full-text) and display the number of users assigned when displaying the search result:
Search result:
I’m not really sure how to craft the index to include the number of users assigned.
One approach is to make a Map-Reduce index on the User entity which would calculate the number of users assigned but there are some questions coming up:
Beta Was this translation helpful? Give feedback.
All reactions