Indexes: Indexing Attachments
The AttachmentsFor
method returns a list of attachments in a given document as well as basic information like Name
or Size
about each of them.
- AttachmentsFor
- AttachmentName
IEnumerable<AttachmentName> AttachmentsFor(object doc);
public string Name;
public string Hash;
public string ContentType;
public long Size;
Creating an index using AttachmentsFor()
The AttachmentsFor
method is available in AbstractIndexCreationTask
.
_1
public class Employees_ByAttachmentDetails :
AbstractIndexCreationTask<Employee, Employees_ByAttachmentDetails.IndexEntry>
{
public class IndexEntry
{
public string EmployeeName { get; set; }
public string[] AttachmentNames { get; set; }
public string[] AttachmentContentTypes { get; set; }
public long[] AttachmentSizes { get; set; }
}
public Employees_ByAttachmentDetails()
{
Map = employees => from employee in employees
// Call 'AttachmentsFor' to get attachments details
let attachments = AttachmentsFor(employee)
select new IndexEntry()
{
// Can index info from document properties:
EmployeeName = employee.FirstName + " " + employee.LastName,
// Index DETAILS of attachments:
AttachmentNames = attachments.Select(x => x.Name).ToArray(),
AttachmentContentTypes = attachments.Select(x => x.ContentType).ToArray(),
AttachmentSizes = attachments.Select(x => x.Size).ToArray()
};
}
}
Querying the index
- Sync
- Async
- DocumentQuery
//return all employees that have an attachment called "cv.pdf"
List<Employee> employees = session
.Query<Employees_ByAttachmentNames.Result, Employees_ByAttachmentNames>()
.Where(x => x.AttachmentNames.Contains("cv.pdf"))
.OfType<Employee>()
.ToList();
//return all employees that have an attachment called "cv.pdf"
List<Employee> employees = await asyncSession
.Query<Employees_ByAttachmentNames.Result, Employees_ByAttachmentNames>()
.Where(x => x.AttachmentNames.Contains("cv.pdf"))
.OfType<Employee>()
.ToListAsync();
//return all employees that have an attachment called "cv.pdf"
List<Employee> employees = session
.Advanced
.DocumentQuery<Employee, Employees_ByAttachmentNames>()
.ContainsAny("AttachmentNames", new[] { "cv.pdf" })
.ToList();