问题
I have a number of commands stored in RavenDb and they all implement ICommand. I want to be able to search on the metadata of last modified and Raven-Entity-Name. I am currently doing a multi map on each command as below:
public class CommandAuditSearch_Index : AbstractMultiMapIndexCreationTask<CommandAuditSearch_Index.Results>
{
public class Results
{
public string CommandType { get; set; }
public DateTime LastModified { get; set; }
}
public CommandAuditSearch_Index()
{
AddMap<NewEmployeeStartCommand>(employees => employees.Select(x => new
{
CommandType = MetadataFor(x).Value<string>("Raven-Entity-Name"),
LastModified = MetadataFor(x).Value<DateTime>("Last-Modified")
}));
AddMap<EmployeeLeaverCommand>(employees => employees.Select(x => new
{
CommandType = MetadataFor(x).Value<string>("Raven-Entity-Name"),
LastModified = MetadataFor(x).Value<DateTime>("Last-Modified")
}));
Index(results => results.CommandType, FieldIndexing.Analyzed);
}
}
I query this as follows:
session.Query<CommandAuditSearch_Index.Results, CommandAuditSearch_Index>()
.Where(x => x.CommandType == commandType && x.LastModified >= DateTime.Today).OfType<ICommand>().ToList();
I know there is an index already built into Raven to get the Tag (entity name) and last modified date but I cant seem to figure out how to get the results as my index above gives me.
can anyone point me in the right direction of a static index where I don't have to have the multi maps as above for each command I have to query that gives me the results as a list of ICommands?
Thanks
Paddy
回答1:
A couple of points:
You don't need to mark a field as analyzed unless you are going to be doing fulltext searching with the
Search
query method. If you are just usingWhere
, there is no advantage to analyzing the index term.If you are looking for metadata values in your results, you simply need to get them from the metadata instead of the document data using
GetMetadataFor
. Reference here.As you said, there's already an index for what you need. The easiest way to query it is using the
LuceneQuery
API.var tag = documentStore.Conventions.GetTypeTagName(theCommand.GetType()); var results = session.Advanced .LuceneQuery<ICommand, RavenDocumentsByEntityName>() .WhereEquals("Tag", tag) .AndAlso() .WhereGreaterThanOrEqual("LastModified", DateTime.Today .ToUniversalTime()) .ToList(); foreach (var result in results) { var md = session.Advanced.GetMetadataFor(result); var entityName = md.Value<string>("Raven-Entity-Name"); var lastModified = md.Value<DateTime>("Last-Modified"); // you can see all the metadata if you like Debug.WriteLine(md.ToString(Formatting.Indented)); }
来源:https://stackoverflow.com/questions/15384010/searching-by-entity-name-and-last-modified-date