Skip to main content

A query tree structure, along with order and paging specifiers, allows a search to be performed against indexed documents held in ElasticSearch. The query API allows any required sub-query structure to be defined and a comprehensive selection of Operators enable individual field level evaluation.

Queries

This example demonstrates a simple search with default ordering and paging options:

Synchronous

C#
using Zengenti.Contensis.Delivery
using Zengenti.Data
using Zengenti.Search

var client = ContensisClient.Create();

var query = new Query(
    Op.Contains("title", "Batman"),
    Op.GreaterThan("runtime", 200)
);

// Execute the search returning entries
PagedList<Entry> entriesResult = client.Entries.Search(query);

// Execute the search returning typed models
PagedList<Movie> moviesResult = client.Entries.Search<Movie>(query);

Asynchronous

C#
using Zengenti.Contensis.Delivery
using Zengenti.Data
using Zengenti.Search

var client = ContensisClient.Create();

// Execute the search asynchronously  returning entries
PagedList<Entry> entriesResult = await client.Entries.SearchAsync(query);

// Execute the search returning typed models
PagedList<Movie> moviesResult = await client.Entries.SearchAsync<Movie>(query);

Parameters

There are a number of parameters available on the various search methods

Name Type Description
fieldLinkDepths Dictionary<string, int> The link depths to resolve link entries to for specific field paths
fields IList<string> The list of fields to return in the entries
linkDepth int The link depth to resolve linked entries to for specific fields
query Query A query object which defines the search to execute
zenQL string A ZenQL query which defines the search to execute

This example carries out a simple search with a link depth of 1 which is overridden for two specific field paths

C#
using Zengenti.Contensis.Delivery
using Zengenti.Data
using Zengenti.Search

var client = ContensisClient.Create();

// Execute the search asynchronously  returning entries
PagedList<Entry> entriesResult = await client.Entries.SearchAsync(query, 1,
    new Dictionary<string, int>{{"entryLink", 3}, {"composer.relatedItems", 2}});

// Execute the search returning typed models
PagedList<Movie> moviesResult = await client.Entries.SearchAsync<Movie>(query, 1,
    new Dictionary<string, int>{{"entryLink", 3}, {"composer.relatedItems", 2}});

Sub-queries

A sub-query is a query within another query that is used as a condition to further restrict the results. Effectively they are defined by an explicit nesting of logical operators.

This example demonstrates a simple search with a sub-query:

Synchronous

C#
var query = new Query(
    Op.Contains("title", "Batman"),
    Op.Or(
        Op.GreaterThan("releaseDate", 1960),
        Op.Contains("tagline", "gotham")
    )
);

Location searches

Search for locations within a radius of a specified location.

Supported distance units

Unit Search value
Mile mi or miles
Yard yd or yards
Feet ft or feet
Inch in or inch
Kilometer km or kilometers
Meter m or meters
Centimeter cm or centimeters
Millimeter mm or millimeters
Nautical mile NM, nmi or nauticalmiles

Example

Find all entries which have a location within 10.5 miles of Ludlow Castle's location.
Append the search value at the end of the distance specified, so for example "10.5mi" or "10.5miles".

C#
var query = new Query(
    Op.DistanceWithin("location", 52.36700505, -2.72304296, "10.5mi")
);

Ordering

Results can be ordered by one or more fields in an ascending or descending direction. Order clauses are prioritised in the order that they are added. By default, if no order clauses are specified then the entry results are ordered by:

  • A relevancy 'score' for each entry for the search query (from ElasticSearch) in a descending direction
  • The EntryTitle in an ascending direction.

This is the best solution for searches using a search term of some kind as it will promote the most relevant results to the top of the results. However, this can occasionally mean that an odd entry might appear on more than one page as the relevancy score is dynamically calculated on each paged request. As such, if you intend to page through the complete result set without any duplicates you should always specify an order by field.

Order by 'releaseDate'.

C#
query.OrderBy.Add("releaseDate");

Order by 'releaseDate' in a descending direction using the '-' token.

C#
query.OrderBy.Add("-releaseDate");

Multiple order clauses.

C#
query.OrderBy.Add("title");
query.OrderBy.Add("-releaseDate");

Paging

Paging allows the number of results to be restricted to a defined count so that the results are easier to handle and ensures a response is returned quickly. The page index can also be specified to indicate the individual page of results to return. If you intend to page through the complete result set without any duplicates you should always specify an order by field. The page size is limited to a maximum of 10,000, however this is not recommended.

C#
// Create a query
var query = new Query(
    Op.EqualTo("sys.contentTypeId", "film")
);

// Set the number of entries to be returned per page
query.PageSize = 50;

// Get the 2nd result set
query.PageIndex = 1;

Specifying fields

System fields

System fields such as id, contentTypeId, projectId, versionNo etc. are under the sys object and can be accessed using a dot notation, e.g. sys.id, sys.contentTypeId, sys.projectId, sys.version.versionNo.

The entryTitle and entryDescription fields are dynamic values, determined by the EntryTitleField and entryDescriptionField values in the content type.

Data fields

Fields defined in the content type for the entry can be accessed by their API id.

All fields

All fields can be searched by specifying an asterisk (*) in the field id. Note there are some limitations, and the FreeText operator is not supported for all fields.

Example

C#
var query = new Query(
    Op.EqualTo("*", "Interstellar")
);

Array fields

Searching on array fields require square brackets [] to be specified in the field id before any field ids within the object. Note that this syntax is not required for single object fields. All operators support searching across array fields.

This example searches for a quote source of "Bruce Willis" within a quote array field called movieQuote.

C#
var query = new Query(
    Op.EqualTo("movieQuote[].source", "Bruce Willis")
);

Limiting fields

If you have large entries and only require a subset of fields it is worth limiting the fields returned in the results. This will reduce the size of the payload from the API which in turn will improve performance. You can include fields by specifiying the field API ID or you can exclude fields by prefixing the field API ID with a -. Field limiting also applies to linked entries when specifying a linkDepth or fieldLinkDepths

Example field limiting

C#
var query = new Query(
    Op.EqualTo("title", "Interstellar")
);

query.Fields = new[] {"title", "movieQuote"};

Complete example

The example below combines the ordering and paging concepts:

C#
using Zengenti.Contensis.Delivery
using Zengenti.Data
using Zengenti.Search

var client = ContensisClient.Create();

var query = new Query(
    Op.Contains("title", "Batman"),
    Op.GreaterThan("runtime", 200)
);

query.OrderBy.Add("-releaseDate")
query.PageIndex = 1;
query.PageSize = 50;
query.Fields = new[] {"title"};

// Execute the search
var results = client.Entries.Search(query);

Still need help?

If you still need help after reading this article, don't hesitate to reach out to the Contensis community on Slack or raise a support ticket to get help from our team.
New support request