Skip to main content

Indexes: Converting to JSON and Accessing Metadata

Entities passed to an index can be converted to JSON using the AsJson method.
It is also possible to access metadata for a specified object using the MetadataFor method.

AsJson - Converting to JSON

public class Products_AllProperties : AbstractIndexCreationTask<Product, Products_AllProperties.Result>
{
public class Result
{
public string Query { get; set; }
}

public Products_AllProperties()
{
Map = products => from product in products
select new
{
// convert product to JSON and select all properties from it
Query = AsJson(product).Select(x => x.Value)
};

// mark 'Query' field as analyzed which enables full text search operations
Index(x => x.Query, FieldIndexing.Search);
}
}
IList<Product> results = session
.Query<Products_AllProperties.Result, Products_AllProperties>()
.Where(x => x.Query == "Chocolade")
.OfType<Product>()
.ToList();

MetadataFor - Accessing Metadata

public class Products_WithMetadata : AbstractIndexCreationTask<Product>
{
public class Result
{
public DateTime LastModified { get; set; }
}

public Products_WithMetadata()
{
Map = products => from product in products
let metadata = MetadataFor(product)
select new
{
LastModified = metadata.Value<DateTime>("@last-modified")
};
}
}
IList<Product> results = session
.Query<Products_WithMetadata.Result, Products_WithMetadata>()
.OrderByDescending(x => x.LastModified)
.OfType<Product>()
.ToList();