Elastic Index
Working with ES indexing.
Mobiz Platform SimpleQuery Handbook
Assumptions
SimpleQuery is an abstraction for querying data stored in an index, this allows for a clean API that can easily be mocked.
- The data stored in index should be viewed as confidential.
- In most cases our queries should respect the current user / organization context.
- There are some cases where we need to escape the context ‘sandbox’.
Query building
The first step in querying index data is to build the query.
Lets assume we store data of type Invoice
in our index as described below.
class Invoice
{
DateTime CreatedAt;
string ItemId;
}
Now if we wanted to query all invoices that have a specific ItemId
sorted in ascending order based on CreatedAt
we could create a query as described below.
SimpleQuery query = new SimpleQuery
{
PageSize = ServiceConstants.MAX_PAGE_SIZE,
SortFields = new List<SimpleQuerySortField>
{
new SimpleQuerySortField
{
OrderBy = "CreatedAt",
}
},
Clauses = new List<SimpleQueryClause>()
{
new SimpleQueryClause
{
WhereField = "ItemId",
Operator = SimpleQueryOperator.Equals,
MatchValue = itemId
}
}
};
Query execution
Scoped
As briefly mentioned, in most cases, we want to respect the context of the organization or user making the request. This is done by executing IMobizIndexService.RunSimpleQuery
with our query as described below.
var service = serviceCollection.GetOrganizationIndexService(orgContext, "MyExtension");
var res = service.RunSimpleQuery<Invoice>(qry);
This will return all invoices matching the ItemId and scoped to a organization context. In other words, all invoices belonging to an Organization with a specific ItemId
.
Unscoped
There are however cases when we need to search the index for data possibly belonging to multiple organizations. Mobiz provides IMobizIndexManager
for this occasion.
This can be achieved by executing IMobizIndexManager.RunSimpleQuery
with our query as described below.
var manager = serviceCollection.GetIndexManagerService();
var service = serviceCollection.GetOrganizationIndexService(orgContext, "MyExtension");
var res = manager.RunSimpleQuery<Invoice>(service, qry);
This will return all invoices matching the ItemId. In other words, all invoices with a specific ItemId
NOTE: Running queries outside the Mobiz context ‘sandbox’ should always be done with care as the responsibility for data integrity is in your hands.