You are currently browsing legacy 4.1 version of documentation. Click here to switch to the newest 4.2 version.

We can help you with migration to the latest RavenDB

Contact Us Now
see on GitHub

Indexes: Converting to JSON and Accessing Metadata

Entities passed to an index can be converted to JSON using AsJson method. There is also a possibility to access metadata for a specified object using 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();