Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a LIKE query in Azure CosmosDB?

I want to retrieve data from Cosmos DB with the following query:

SELECT * FROM c WHERE c.pi like '09%001' 

(This is a SQL query, which I can use in MySQL)

Here, pi is a string value, which can be 09001001 or 09025001.

Is there a way to use a LIKE command in Cosmos DB?

I know that cosmos DB uses CONTAINS, but this cannot be used when you want to match specifically the beginning or end of the string.

like image 510
arjan kroon Avatar asked May 29 '18 06:05

arjan kroon


People also ask

Is Cosmos DB like MongoDB?

Cosmos DB is positioned as providing a globally scalable, multi-model database supporting operational applications. It borrows many concepts from MongoDB, but falls short in compatibility and functionality. For example, you can only query data using a single model.

Can you use SQL in Cosmos DB?

Azure Cosmos DB supports several APIs like Core (SQL), Cassandra (to access Columnar data), Gremlin (for Graph data), MongoDB API (for Document data), and Azure Table (Azure Table Storage for Key-value data) that can be used to access a variety of data.

How do I extract data from Cosmos DB?

There are a few methods to export data from Cosmos DB. The quickest one is to use Document DB / Cosmos DB Migration Tool. This is a tool provided by Microsoft to migrate data TO/FROM various sources such as MongoDB, JSON, csv and SQL Server to Cosmos DB.


1 Answers

UPDATE :

You can now use the LIKE keyword to do text searches in Azure Cosmos DB SQL (core) API!

EXAMPLE:

SELECT * FROM c WHERE c.description LIKE "%cereal%" 

OLD Answer:

This can be achieved in 2 ways

(i) Currently Azure Cosmosdb supports the CONTAINS, STARTSWITH, and ENDSWITH built-in functions which are equivalent to LIKE.

The keyword for LIKE in Cosmosdb is Contains .

SELECT * FROM c WHERE CONTAINS(c.pi, '09') 

So, in your case if you want to match the pattern 09%001, you need to use:

SELECT * FROM c WHERE STARTSWITH(c.pi, '09') AND ENDSWITH(c.pi, '001') 

(ii) As 404 mentioned, Use SQL API User Defined Functions which supports regex :

function executeRegex(str, pattern) {     let regex=RegExp(pattern);     return regex.test(str); }  SELECT udf.EXECUTE_REGEX("foobar", ".*bar") 
like image 104
Sajeetharan Avatar answered Sep 26 '22 15:09

Sajeetharan