### Install @shellicar/cosmos-query-builder Source: https://github.com/shellicar/cosmos-query-builder/blob/main/packages/cosmos-query-builder/README.md Commands to install the package using common Node.js package managers. Choose the command based on your preferred tool. ```bash npm i --save @shellicar/cosmos-query-builder ``` ```bash pnpm add @shellicar/cosmos-query-builder ``` -------------------------------- ### Full Usage Example of Cosmos Query Builder (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md A comprehensive example showcasing the setup and usage of the Cosmos Query Builder for fetching data from Azure Cosmos DB. It includes type definitions, query construction, and data retrieval. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; import type { Container } from '@azure/cosmos'; type Person = { id: string; type: 'Person'; age: number; created: string; name: { givenName: string; familyName: string; }; }; const queryPeople = async (container: Container) => { const builder = createCosmosQueryBuilder(); builder.where('type', 'eq', 'Person'); builder.where('age', 'gt', 18); builder.orderBy('created', SortDirection.Desc); builder.limit(50); const results = await builder.getAll(container); console.log(`Found ${results.count} people`); return results.items; }; ``` -------------------------------- ### Install @shellicar/cosmos-query-builder using pnpm Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md This snippet demonstrates how to install the @shellicar/cosmos-query-builder package using pnpm. This is an alternative package manager for installing the library. ```sh pnpm add @shellicar/cosmos-query-builder ``` -------------------------------- ### Patch Operations for Cosmos DB (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md Provides an example of creating type-safe JSON patch documents for Cosmos DB operations. This allows for efficient and safe updates to existing documents in the database. ```typescript const operations = builder.patch({ op: 'replace', path: '/name/givenName', value: 'Smith' }); await container.item('id', 'partitionKey').patch(operations); ``` -------------------------------- ### OR Clause for Multiple Conditions (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds an OR clause to match items satisfying any of the given conditions. Useful for complex filtering logic that requires combining multiple conditions with OR. This example finds people by name or role. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: { givenName: string; familyName: string }; role: string; }; const builder = createCosmosQueryBuilder(); // Find people named John OR Smith OR with admin role builder.whereOr([ { field: 'name.givenName', operator: 'eq', value: 'John' }, { field: 'name.familyName', operator: 'eq', value: 'Smith' }, { field: 'name.familyName', operator: 'ieq', value: 'smith' }, // case-insensitive { field: 'role', operator: 'eq', value: 'admin' } ]); const query = builder.query(); /* SELECT * FROM c WHERE (c.name.givenName = @p0 OR c.name.familyName = @p1 OR StringEquals(c.name.familyName, @p2, true) OR c.role = @p3) */ ``` -------------------------------- ### Raw WHERE Clause for Joined Aliases (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds an untyped WHERE clause with field path as string. Use this for filtering on joined aliases or when type safety is not needed. This example joins an 'items' array and filters by productId and quantity. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Order = { id: string; items: { productId: string; quantity: number }[]; }; const builder = createCosmosQueryBuilder(); // Join items array builder.join('i', 'items'); // Use whereRaw for the joined alias builder.whereRaw('i.productId', 'eq', 'prod-123'); builder.whereRaw('i.quantity', 'gt', 5); const query = builder.query(); /* SELECT * FROM c JOIN i IN c.items WHERE i.productId = @p0 AND i.quantity > @p1 */ ``` -------------------------------- ### GROUP BY Clause for Aggregation (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Sets the GROUP BY clause for aggregation queries. Typically used with a custom select clause for aggregate functions. This example aggregates order counts and total amounts by status. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Order = { id: string; customerId: string; total: number; status: string; }; const builder = createCosmosQueryBuilder(); builder.select('c.status, COUNT(1) as orderCount, SUM(c.total) as totalAmount'); builder.groupBy('c.status'); const query = builder.query(); /* SELECT c.status, COUNT(1) as orderCount, SUM(c.total) as totalAmount FROM c GROUP BY c.status */ ``` -------------------------------- ### Custom SELECT Clause with Aggregation (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Sets a custom SELECT clause for projections, aggregations, or computed fields. Note that custom select does not provide type safety. This example demonstrates counting and grouping by a field. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; type Person = { id: string; sex: string; name: { givenName: string; familyName: string }; }; const builder = createCosmosQueryBuilder(); // Custom projection with aggregation builder.select('COUNT(1) as count, UPPER(c.sex) as sex'); builder.groupBy('UPPER(c.sex)'); const query = builder.query(); /* SELECT COUNT(1) as count, UPPER(c.sex) as sex FROM c GROUP BY UPPER(c.sex) */ ``` -------------------------------- ### JOIN Clause for Nested Arrays (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds a JOIN clause to query nested arrays in Cosmos DB documents. The join creates an alias that can be used with whereRaw for filtering on joined elements. This example joins a 'products' array and filters by price and name. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: string; products: { id: string; name: string; price: number }[]; }; const builder = createCosmosQueryBuilder(); // Join on the products array with alias 'p' builder.join('p', 'products'); // Filter on joined items using whereRaw builder.whereRaw('p.price', 'gt', 100); builder.whereRaw('p.name', 'eq', 'Premium Widget'); const query = builder.query(); /* SELECT * FROM c JOIN p IN c.products WHERE p.price > @p0 AND p.name = @p1 */ ``` -------------------------------- ### Construct and Execute Cosmos DB Queries Source: https://github.com/shellicar/cosmos-query-builder/blob/main/packages/cosmos-query-builder/README.md Demonstrates how to initialize the query builder with a type, apply filters, set sorting, and execute the query against a Cosmos DB container. This approach ensures type safety when querying documents. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; const builder = createCosmosQueryBuilder(); builder.where('type', 'eq', 'Person'); builder.where('age', 'gt', 18); builder.orderBy('created', SortDirection.Desc); builder.limit(50); const results = await builder.getAll(container); ``` -------------------------------- ### Execute Paginated Queries with getAll Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Executes a query and retrieves results with pagination support. It returns a result object containing the items, total count, and a continuation token for fetching subsequent pages. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; import type { Container } from '@azure/cosmos'; type Person = { id: string; name: string; age: number; created: string; }; async function fetchPaginatedResults(container: Container) { const builder = createCosmosQueryBuilder(); builder.where('age', 'gt', 18); builder.orderBy('created', SortDirection.Desc); const firstPage = await builder.getAll(container, 25); console.log({ items: firstPage.items, count: firstPage.count, totalCount: firstPage.totalCount, hasMoreResults: firstPage.hasMoreResults, continuationToken: firstPage.continuationToken }); if (firstPage.hasMoreResults) { const secondPage = await builder.getAll(container, 25, firstPage.continuationToken); console.log(`Page 2: ${secondPage.count} items`); } return firstPage.items; } ``` -------------------------------- ### Builder Pattern for Cosmos DB Queries (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md Demonstrates the builder pattern for constructing Cosmos DB queries using methods like `where()`, `orderBy()`, and `limit()`. This approach avoids writing raw SQL and enhances code readability. ```typescript builder.where('type', 'eq', 'Person'); builder.where('age', 'gt', 18); builder.orderBy('created', SortDirection.Desc); builder.limit(50); ``` -------------------------------- ### Implement Custom Logging with ILogger Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Allows integration with external logging frameworks by extending the ILogger interface. The custom logger can be passed into the builder options to track query construction and execution details. ```typescript import { createCosmosQueryBuilder, ILogger } from '@shellicar/cosmos-query-builder'; class ConsoleLogger extends ILogger { debug(message?: any, ...params: any[]): void { console.debug('[DEBUG]', message, ...params); } info(message?: any, ...params: any[]): void { console.info('[INFO]', message, ...params); } warn(message?: any, ...params: any[]): void { console.warn('[WARN]', message, ...params); } error(message?: any, ...params: any[]): void { console.error('[ERROR]', message, ...params); } verbose(message?: any, ...params: any[]): void { console.log('[VERBOSE]', message, ...params); } } const builder = createCosmosQueryBuilder<{ id: string }>({ logger: new ConsoleLogger() }); builder.where('id', 'eq', 'test-123'); const query = builder.query(); ``` -------------------------------- ### Retrieve Single Result with getOne Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Executes the query and returns the first matching document. Returns null if no documents satisfy the query criteria. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; import type { Container } from '@azure/cosmos'; type User = { id: string; email: string; name: string; role: string; }; async function findUserByEmail(container: Container, email: string): Promise { const builder = createCosmosQueryBuilder(); builder.where('email', 'ieq', email); builder.limit(1); const user = await builder.getOne(container); if (user === null) { console.log('User not found'); return null; } console.log(`Found user: ${user.name} (${user.role})`); return user; } ``` -------------------------------- ### Build and Execute Type-Safe Cosmos DB Queries in TypeScript Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt This TypeScript code demonstrates how to build and execute a complex query against Azure Cosmos DB. It defines custom types for documents and filters, uses the query builder to construct a query with multiple conditions (type, deleted status, age range, fuzzy search), sorts the results, limits the output, and handles potential errors during execution. It requires the `@azure/cosmos` and `@shellicar/cosmos-query-builder` packages. ```typescript import type { UUID } from 'node:crypto'; import { CosmosClient, type Container } from '@azure/cosmos'; import { createCosmosQueryBuilder, SortDirection, type StringFilter } from '@shellicar/cosmos-query-builder'; // Define document type with nested structures type Person = { id: UUID; type: 'Person'; created: string; modified: string; deleted?: string | null; name: { givenName: string; familyName: string; }; email: string; age: number; tags: string[]; }; // Define filter type for structured queries type PersonFilter = { name?: { givenName?: StringFilter; familyName?: StringFilter; }; }; async function searchPeople(container: Container, searchTerm: string) { const builder = createCosmosQueryBuilder(); // Filter by document type builder.where('type', 'eq', 'Person'); // Exclude deleted documents builder.where('deleted', 'isNull'); // Age range builder.where('age', 'ge', 18); builder.where('age', 'le', 65); // Fuzzy search across name fields and email builder.whereFuzzy(searchTerm, ['name.givenName', 'name.familyName', 'email']); // Sort by creation date, newest first builder.orderBy('created', SortDirection.Desc); // Limit results builder.limit(50); try { const results = await builder.getAll(container); console.log(`Found ${results.count} of ${results.totalCount} matching people`); for (const person of results.items) { console.log(`- ${person.name.givenName} ${person.name.familyName} (${person.email})`); } return results; } catch (error) { console.error('Query failed:', error); throw error; } } // Initialize Cosmos DB client const client = new CosmosClient(process.env.COSMOS_CONNECTION_STRING ?? ''); const container = client.database('mydb').container('people'); // Execute search await searchPeople(container, 'john'); ``` -------------------------------- ### Set ORDER BY Clause for Query Results Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Demonstrates setting the ORDER BY clause for query results using a type-safe field path and sort direction. The `orderBy` method can be called without arguments to clear any existing ordering. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; type Product = { id: string; name: string; price: number; created: string; }; const builder = createCosmosQueryBuilder(); // Order by created date descending builder.orderBy('created', SortDirection.Desc); // Or ascending builder.orderBy('price', SortDirection.Asc); // Clear ordering builder.orderBy(); const query = builder.query(); /* SELECT * FROM c ORDER BY c.price ASC */ ``` -------------------------------- ### Type-Safe Field Access in Cosmos DB Queries (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md Shows how to leverage type-safe field access for IntelliSense and compile-time validation of field paths and values in Cosmos DB queries. This helps prevent common errors related to incorrect field names or value types. ```typescript // @ts-expect-error: Argument of type 'number' is not assignable to parameter of type 'string'. builder.where('age', 'eq', 'invalid'); builder.where('age', 'eq', 25); ``` -------------------------------- ### Set LIMIT Clause for Query Results Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Shows how to set the maximum number of items to return from a query using the `limit` method. This adds OFFSET 0 and LIMIT clauses to the generated SQL query. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Document = { id: string; title: string }; const builder = createCosmosQueryBuilder(); builder.where('title', 'ne', ''); builder.limit(100); const query = builder.query(); /* SELECT * FROM c WHERE c.title != @p0 OFFSET 0 LIMIT 100 */ ``` -------------------------------- ### Create Type-Safe Cosmos Query Builder Instance Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Demonstrates creating a type-safe query builder instance using `createCosmosQueryBuilder`. The generic type `T` ensures type safety for document fields and values throughout query construction. It shows basic filtering, ordering, and limiting, followed by query execution. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; import type { Container } from '@azure/cosmos'; type Person = { id: string; type: 'Person'; age: number; created: string; name: { givenName: string; familyName: string; }; }; // Create a type-safe query builder for Person documents const builder = createCosmosQueryBuilder(); // Build and execute the query builder.where('type', 'eq', 'Person'); builder.where('age', 'gt', 18); builder.orderBy('created', SortDirection.Desc); builder.limit(50); const results = await builder.getAll(container); console.log(`Found ${results.count} people`); // Output: Found 25 people ``` -------------------------------- ### Structured Filtering for Cosmos DB Queries (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md Demonstrates structured filtering using filter objects with type information for complex queries in Cosmos DB. This method enhances query clarity and maintainability for intricate filtering logic. ```typescript type PersonFilter = { name?: { givenName?: StringFilter; }; }; const filter = { name: { givenName: { __typeInfo: 'StringFilter', eq: 'John' } } } satisfies PersonFilter; builder.buildQuery(filter); ``` -------------------------------- ### Generate final SQL query specifications Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt The query method returns a SqlQuerySpec object containing the generated SQL string and the corresponding parameters. This object is directly compatible with the Azure Cosmos DB SDK. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; type Product = { id: string; name: string; price: number; category: string }; const builder = createCosmosQueryBuilder(); builder.where('category', 'eq', 'Electronics'); builder.where('price', 'lt', 1000); builder.orderBy('price', SortDirection.Asc); builder.limit(10); const querySpec = builder.query(); console.log(querySpec.query); console.log(querySpec.parameters); ``` -------------------------------- ### WHERE OR - Combining Conditions with OR Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds an OR clause to match items satisfying any of the given conditions. Useful for complex filtering logic that requires combining multiple conditions with OR. ```APIDOC ## WHERE OR ### Description Adds an OR clause to match items satisfying any of the given conditions. Useful for complex filtering logic that requires combining multiple conditions with OR. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: { givenName: string; familyName: string }; role: string; }; const builder = createCosmosQueryBuilder(); // Find people named John OR Smith OR with admin role builder.whereOr([ { field: 'name.givenName', operator: 'eq', value: 'John' }, { field: 'name.familyName', operator: 'eq', value: 'Smith' }, { field: 'name.familyName', operator: 'ieq', value: 'smith' }, // case-insensitive { field: 'role', operator: 'eq', value: 'admin' } ]); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT * FROM c WHERE (c.name.givenName = @p0 OR c.name.familyName = @p1 OR StringEquals(c.name.familyName, @p2, true) OR c.role = @p3) ``` ``` -------------------------------- ### Add WHERE Clause with Type-Safe Operators Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Illustrates adding a WHERE clause using type-safe field access and various operators. Supports equality, comparisons, null checks, array containment, and IN operations. Field paths are validated at compile time. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; age: number; name: { givenName: string; familyName: string }; tags: string[]; deletedAt?: string | null; }; const builder = createCosmosQueryBuilder(); // Basic equality builder.where('name.givenName', 'eq', 'John'); // Comparison operators: gt, lt, ge, le, ne builder.where('age', 'gt', 18); builder.where('age', 'le', 65); // Case-insensitive equality (ieq) and inequality (ine) builder.where('name.familyName', 'ieq', 'smith'); // matches Smith, SMITH, smith builder.where('name.givenName', 'ine', 'admin'); // excludes admin case-insensitively // Check for null values builder.where('deletedAt', 'isNull'); // Array contains - check if field array contains a value builder.where('tags', 'contains', 'developer'); // IN operator - check if field value is in provided array builder.where('name.givenName', 'in', ['John', 'Jane', 'Bob']); const query = builder.query(); // Generates parameterized SQL with @p0, @p1, etc. ``` -------------------------------- ### Build structured queries with type annotations Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt The buildQuery method converts a structured filter object into SQL conditions. It supports various filter types like StringFilter, UUIDFilter, and InstantFilter, ensuring type safety and correct operator mapping. ```typescript import { createCosmosQueryBuilder, type StringFilter, type UUIDFilter } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: { givenName: string; familyName: string }; email: string; }; type PersonFilter = { id?: UUIDFilter; name?: { givenName?: StringFilter; familyName?: StringFilter; }; email?: StringFilter; }; const builder = createCosmosQueryBuilder(); const filter: PersonFilter = { name: { givenName: { __typeInfo: 'StringFilter', eq: 'John' }, familyName: { __typeInfo: 'StringFilter', like: 'Smith' } }, email: { __typeInfo: 'StringFilter', ine: 'admin@test.com' } }; builder.buildQuery(filter); const query = builder.query(); ``` -------------------------------- ### WHERE RAW - Untyped WHERE Clause Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds an untyped WHERE clause with field path as string. Use this for filtering on joined aliases or when type safety is not needed. ```APIDOC ## WHERE RAW ### Description Adds an untyped WHERE clause with field path as string. Use this for filtering on joined aliases or when type safety is not needed. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Order = { id: string; items: { productId: string; quantity: number }[]; }; const builder = createCosmosQueryBuilder(); // Join items array builder.join('i', 'items'); // Use whereRaw for the joined alias builder.whereRaw('i.productId', 'eq', 'prod-123'); builder.whereRaw('i.quantity', 'gt', 5); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT * FROM c JOIN i IN c.items WHERE i.productId = @p0 AND i.quantity > @p1 ``` ``` -------------------------------- ### Create type-safe JSON patch operations Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt The patch method generates operations for partial document updates in Cosmos DB. It supports set, add, replace, and remove operations while providing compile-time path validation against the document schema. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; import type { Container } from '@azure/cosmos'; type Person = { id: string; name: { givenName: string; familyName: string }; age: number; tags: string[] }; const builder = createCosmosQueryBuilder(); const operations = builder.patch( { op: 'replace', path: '/name/givenName', value: 'Jane' }, { op: 'set', path: '/age', value: 30 }, { op: 'add', path: '/tags', value: ['verified'] }, { op: 'remove', path: '/name/familyName' } ); // Apply patch to specific document const container: Container = /* your container */; const item = container.item('document-id', 'partition-key'); await item.patch(operations); ``` -------------------------------- ### JOIN Clause - Querying Nested Arrays Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Adds a JOIN clause to query nested arrays in Cosmos DB documents. The join creates an alias that can be used with whereRaw for filtering on joined elements. ```APIDOC ## JOIN ### Description Adds a JOIN clause to query nested arrays in Cosmos DB documents. The join creates an alias that can be used with whereRaw for filtering on joined elements. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: string; products: { id: string; name: string; price: number }[]; }; const builder = createCosmosQueryBuilder(); // Join on the products array with alias 'p' builder.join('p', 'products'); // Filter on joined items using whereRaw builder.whereRaw('p.price', 'gt', 100); builder.whereRaw('p.name', 'eq', 'Premium Widget'); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT * FROM c JOIN p IN c.products WHERE p.price > @p0 AND p.name = @p1 ``` ``` -------------------------------- ### Add custom WHERE clauses with TypeScript Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt The filter method allows for the injection of raw SQL WHERE clauses into the query builder. It supports optional parameterization using the '@' placeholder, which is automatically mapped to generated parameter names. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Document = { id: string; data: Record }; const builder = createCosmosQueryBuilder(); // Custom clause with parameter builder.filter({ clause: 'ARRAY_LENGTH(c.data.items) > @', parameter: 10 }); // Custom clause without parameter builder.filter({ clause: 'IS_DEFINED(c.data.metadata)' }); const query = builder.query(); ``` -------------------------------- ### Apply Sorting with SortDirection Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Uses the SortDirection enumeration to define ascending or descending order in query results. This ensures type-safe configuration for orderBy clauses. ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; type Event = { id: string; timestamp: string; priority: number; }; const builder = createCosmosQueryBuilder(); builder.orderBy('timestamp', SortDirection.Asc); builder.orderBy('timestamp', SortDirection.Desc); ``` -------------------------------- ### SELECT Clause - Custom Projections and Aggregations Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Sets a custom SELECT clause for the query. Use this for projections, aggregations, or computed fields. Note that custom select does not provide type safety. ```APIDOC ## SELECT ### Description Sets a custom SELECT clause for the query. Use this for projections, aggregations, or computed fields. Note that custom select does not provide type safety. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder, SortDirection } from '@shellicar/cosmos-query-builder'; type Person = { id: string; sex: string; name: { givenName: string; familyName: string }; }; const builder = createCosmosQueryBuilder(); // Custom projection with aggregation builder.select('COUNT(1) as count, UPPER(c.sex) as sex'); builder.groupBy('UPPER(c.sex)'); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT COUNT(1) as count, UPPER(c.sex) as sex FROM c GROUP BY UPPER(c.sex) ``` ``` -------------------------------- ### Advanced Operators for Cosmos DB Queries (TypeScript) Source: https://github.com/shellicar/cosmos-query-builder/blob/main/README.md Illustrates the use of advanced operators for array operations (e.g., `contains`, `in`) and fuzzy search across multiple fields in Cosmos DB queries. These operators allow for more flexible and powerful data filtering. ```typescript builder.where('bones', 'contains', 'arm'); builder.where('name.givenName', 'in', ['John', 'Jane']); builder.whereFuzzy('steve', ['name.givenName', 'name.familyName', 'email']); ``` -------------------------------- ### GROUP BY Clause - Aggregation Queries Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Sets the GROUP BY clause for aggregation queries. Typically used with a custom select clause for aggregate functions. ```APIDOC ## GROUP BY ### Description Sets the GROUP BY clause for aggregation queries. Typically used with a custom select clause for aggregate functions. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Order = { id: string; customerId: string; total: number; status: string; }; const builder = createCosmosQueryBuilder(); builder.select('c.status, COUNT(1) as orderCount, SUM(c.total) as totalAmount'); builder.groupBy('c.status'); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT c.status, COUNT(1) as orderCount, SUM(c.total) as totalAmount FROM c GROUP BY c.status ``` ``` -------------------------------- ### Fuzzy Search Across Multiple Fields (TypeScript) Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Performs case-insensitive fuzzy search across multiple fields. Generates an OR condition that checks if any of the specified fields contain the search term. The 'true' parameter enables case-insensitive matching. ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: { givenName: string; familyName: string }; email: string; phone: string; }; const builder = createCosmosQueryBuilder(); // Search for 'steve' across multiple fields builder.whereFuzzy('steve', ['name.givenName', 'name.familyName', 'email']); const query = builder.query(); /* SELECT * FROM c WHERE (Contains(c.name.givenName, @p0, true) OR Contains(c.name.familyName, @p0, true) OR Contains(c.email, @p0, true)) */ // The 'true' parameter enables case-insensitive matching ``` -------------------------------- ### WHERE FUZZY - Case-Insensitive Fuzzy Search Source: https://context7.com/shellicar/cosmos-query-builder/llms.txt Performs case-insensitive fuzzy search across multiple fields. Generates an OR condition that checks if any of the specified fields contain the search term. ```APIDOC ## WHERE FUZZY ### Description Performs case-insensitive fuzzy search across multiple fields. Generates an OR condition that checks if any of the specified fields contain the search term. ### Method Not Applicable (Method is called on the builder instance) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createCosmosQueryBuilder } from '@shellicar/cosmos-query-builder'; type Person = { id: string; name: { givenName: string; familyName: string }; email: string; phone: string; }; const builder = createCosmosQueryBuilder(); // Search for 'steve' across multiple fields builder.whereFuzzy('steve', ['name.givenName', 'name.familyName', 'email']); const query = builder.query(); ``` ### Response #### Success Response (200) Not Applicable (This is a query builder, not an endpoint) #### Response Example ```sql SELECT * FROM c WHERE (Contains(c.name.givenName, @p0, true) OR Contains(c.name.familyName, @p0, true) OR Contains(c.email, @p0, true)) ``` * The 'true' parameter enables case-insensitive matching ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.