Building Your Own Rest Query Language - An Experiment With Azure Cosmos Db

For all the REST resources we deploy out every day, one of the most common scenario a developer ends up handling is designing a nice and effective search/filter/query endpoint for these aforementioned resources. Usually, in these scenarios, conventions play a big part and that starts from query filter parameters in the query string to using a full blown search engine like ElasticSearch, Lucene or Algolia. 

Today, we will do a simple yet fun experiment. Our goal today is to create a simple nifty looking query language for a sample REST resource. We will try to mimic a couple of features Twitter Search API provides and our sample data storage today will be Azure CosmosDB: DocumentDB which previously was known as just Azure DocumentDB has now moved to the Azure CosmosDB family.

Therefore, the first thing we need is a set of sample data that we can use as our REST resource. Since we are going to mimic the Twitter public search API, we definitely need some sample data first. And, of course, GitHub comes to the rescue. Download the sample data and put it to your own document db instance. If you don't know how to create a document db instance, follow the quick start here. I'm referencing the link to the .NET quick start, but there are node.js, Python, Java, and Xamarin resources right by the side of it. For those of you who do not want to test your work against an Azure hosted DocumentDB and want to test Azure DocumentDB locally, you can always opt for the Azure DocumentDB emulator.

Now, for the sake of this experiment, I ported the GitHub Twitter sample data to an Azure DocumentDB instance. It has 10 entries in that small data set and hosted here. If you want to browse the data, Azure portal does allow it. But I suggest looking at this open source app here named Azure DocumentDB Studio. You can use the endpoint and the key written in the sample code in GitHub to connect. The database is public just for you guys so you can test the sample code I have hosted in GitHub and will list out in the end of this article.

Note - TL;DR people, this is your cue to go to the end of the article, but I highly suggest to stick around.

Features to be built

Out of all the features Twitter's Search API provides, I will port the to:UserAccount, from:UserAccount and "exact text" search capabilities. That means, we will be able to search the tweets sent from one account to other and we will also be able to search tweets by mentioning a string we like to be present in the tweets. For an example, if we want to find tweets

  1. from a user account named @terminator
  2. to another user account named @robocop
  3. or any tweet where the words "I'm back"
  4. or the hashtag #HastaLaVista is present,

our sample query language excerpt will be

"http://our-awesome-api/search/q?to:robocop AND from:terminator OR "I'm back" OR #HastaLaVista"

If you have an eye for detail, you will notice that this is not exactly like the Twtter Search API since it doesn't use an and operator. But for the sake of the simplicity, in this example, this should be enough.

Tools we are going to use

Our API stack will be written in ASP.NET Core. We will use ANTLR as our query language lexer-parser. If you need an ANTLR primer and another experiment I did with it, please have a look here where I tried to gobble up a simple scripting language. If you are not really accustomed to any of .NET stacks, fret not; all of these are totally doable in any other tech stack you will possibly prefer to use. Since ANTLR has targets for multiple languages, API can be built in basically any language and even for our sample storage solution Azure DocumentDB here, you have access to multiple client SDKs.

The data

As I mentioned above, we have a little data set of 10 entries. I'm posting a sample entry here so the rest of the tutorial makes sense. One entry points to a single tweet made by a sample user.

  1. {  
  2.   "entities": {  
  3.     "user_mentions": [  
  4.       {  
  5.         "indices": [  
  6.           3,  
  7.           15  
  8.         ],  
  9.         "id_str""178253493",  
  10.         "screen_name""mikalabrags",  
  11.         "name""Mika Labrague",  
  12.         "id": 178253493  
  13.       }  
  14.     ],  
  15.     "urls": [],  
  16.     "hashtags": [ "#Confused" ]  
  17.   },  
  18.   "in_reply_to_screen_name"null,  
  19.   "text""RT @mikalabrags: Bipolar weather #Confused",  
  20.   "id_str""210621130703245313",  
  21.   "place"null,  
  22.   "retweeted_status": {  
  23.     "entities": {  
  24.       "user_mentions": [],  
  25.       "urls": [],  
  26.       "hashtags": []  
  27.     },  
  28.     "in_reply_to_screen_name"null,  
  29.     "text""Bipolar weather",  
  30.     "id_str""210619512855343105",  
  31.     "place"null,  
  32.     "in_reply_to_status_id"null,  
  33.     "contributors"null,  
  34.     "retweet_count": 0,  
  35.     "favorited"false,  
  36.     "truncated"false,  
  37.     "source""http://ubersocial.com",  
  38.     "in_reply_to_status_id_str"null,  
  39.     "created_at""Thu Jun 07 06:29:39 +0000 2012",  
  40.     "in_reply_to_user_id_str"null,  
  41.     "in_reply_to_user_id"null,  
  42.     "user": {  
  43.       "lang""en",  
  44.       "profile_background_image_url""http://a0.twimg.com/profile_background_images/503549271/tumblr_m25lrjIjgT1qb6nmgo1_500.jpg",  
  45.       "id_str""178253493",  
  46.       "default_profile_image"false,  
  47.       "statuses_count": 13635,  
  48.       "profile_link_color""06544a",  
  49.       "favourites_count": 819,  
  50.       "profile_image_url_https""https://si0.twimg.com/profile_images/2240536982/AtRKA77CIAAJRHT_normal.jpg",  
  51.       "following"null,  
  52.       "profile_background_color""373d3a",  
  53.       "description""No fate but what we make",  
  54.       "notifications"null,  
  55.       "profile_background_tile"true,  
  56.       "time_zone""Alaska",  
  57.       "profile_sidebar_fill_color""1c1c21",  
  58.       "listed_count": 1,  
  59.       "contributors_enabled"false,  
  60.       "geo_enabled"true,  
  61.       "created_at""Sat Aug 14 07:31:28 +0000 2010",  
  62.       "screen_name""mikalabrags",  
  63.       "follow_request_sent"null,  
  64.       "profile_sidebar_border_color""08080a",  
  65.       "protected"false,  
  66.       "url"null,  
  67.       "default_profile"false,  
  68.       "name""Mika Labrague",  
  69.       "is_translator"false,  
  70.       "show_all_inline_media"true,  
  71.       "verified"false,  
  72.       "profile_use_background_image"true,  
  73.       "followers_count": 214,  
  74.       "profile_image_url""http://a0.twimg.com/profile_images/2240536982/AtRKA77CIAAJRHT_normal.jpg",  
  75.       "id": 178253493,  
  76.       "profile_background_image_url_https""https://si0.twimg.com/profile_background_images/503549271/tumblr_m25lrjIjgT1qb6nmgo1_500.jpg",  
  77.       "utc_offset": -32400,  
  78.       "friends_count": 224,  
  79.       "profile_text_color""352e4d",  
  80.       "location""Mnl"  
  81.     },  
  82.     "retweeted"false,  
  83.     "id": 2.106195128553431E+17,  
  84.     "coordinates"null,  
  85.     "geo"null  
  86.   },  
  87.   "in_reply_to_status_id"null,  
  88.   "contributors"null,  
  89.   "retweet_count": 0,  
  90.   "favorited"false,  
  91.   "truncated"false,  
  92.   "source""<a href=\"http://blackberry.com/twitter\" rel=\"nofollow\">Twitter for BlackBerry®</a>",  
  93.   "in_reply_to_status_id_str"null,  
  94.   "created_at""Thu Jun 07 06:36:05 +0000 2012",  
  95.   "in_reply_to_user_id_str"null,  
  96.   "in_reply_to_user_id"null,  
  97.   "user": {  
  98.     "lang""en",  
  99.     "profile_background_image_url""http://a0.twimg.com/profile_background_images/542537222/534075_10150809727636812_541871811_10087628_844237475_n_large.jpg",  
  100.     "id_str""37200018",  
  101.     "default_profile_image"false,  
  102.     "statuses_count": 5715,  
  103.     "profile_link_color""CC3366",  
  104.     "favourites_count": 46,  
  105.     "profile_image_url_https""https://si0.twimg.com/profile_images/2276155427/photo_201_1_normal.jpg",  
  106.     "following"null,  
  107.     "profile_background_color""dbe9ed",  
  108.     "description""protège-moi de mes désirs ï£« 23107961 ☍",  
  109.     "notifications"null,  
  110.     "profile_background_tile"true,  
  111.     "time_zone""Singapore",  
  112.     "profile_sidebar_fill_color""ffffff",  
  113.     "listed_count": 2,  
  114.     "contributors_enabled"false,  
  115.     "geo_enabled"true,  
  116.     "created_at""Sat May 02 13:55:49 +0000 2009",  
  117.     "screen_name""yoursweetiethea",  
  118.     "follow_request_sent"null,  
  119.     "profile_sidebar_border_color""91f50e",  
  120.     "protected"false,  
  121.     "url""http://yoursweetiethea.tumblr.com",  
  122.     "default_profile"false,  
  123.     "name""Althea Arellano",  
  124.     "is_translator"false,  
  125.     "show_all_inline_media"false,  
  126.     "verified"false,  
  127.     "profile_use_background_image"true,  
  128.     "followers_count": 306,  
  129.     "profile_image_url""http://a0.twimg.com/profile_images/2276155427/photo_201_1_normal.jpg",  
  130.     "id""37200018",  
  131.     "profile_background_image_url_https""https://si0.twimg.com/profile_background_images/542537222/534075_10150809727636812_541871811_10087628_844237475_n_large.jpg",  
  132.     "utc_offset": 28800,  
  133.     "friends_count": 297,  
  134.     "profile_text_color""fa3c6b",  
  135.     "location""Christian's Heart"  
  136.   },  
  137.   "retweeted"false,  
  138.   "id""210621130703245300",  
  139.   "coordinates"null,  
  140.   "geo"null  
  141. }  

The ANTLR grammar

The ANTLR grammar we are going to use here is,

  1. grammar Search;  
  2.   
  3. expr: term (op term)*;  
  4. term: exactText | hashText | toText | fromText;  
  5. op: AND | OR;  
  6.   
  7. toText: 'to:'ID;  
  8. fromText: 'from:'ID;  
  9. hashText: '#'ID;  
  10. exactText: EXACTTEXT;  
  11.   
  12. // lexer rule  
  13. EXACTTEXT: '"' ~'"'* '"';  
  14. OR: 'OR';  
  15. AND: 'AND';  
  16. ID: [a-zA-Z_] [a-zA-Z0-9_]*;  
  17. WS: [ \n\t\r]+ -> skip;  
 It's a small and simple grammar like the one we used in our scripting language tutorial. Since our REST resource query is essentially an expression, our entry rule will be expr. The railroad diagram for expr looks like the following.
 
 
 
This means we can have a single search term or multiple search terms chained by an op rule. The op rule is nothing but the two relational operator we support: AND and OR.
 
 
Along side of the op rule, we also need to know what the term rule stands for. The term rule stands for the search term format we are allowed to use. In our sample query stated above, we have terms like from:terminator, to:robocop, "I'm back" or a hashtag like #HastaLaVista. That's why we have 4 rules defining all of these cases and the term rule is a OR relationship between them.
 
 

I'm not going to post the railroad diagram for toText, fromText, hashText and exactText rules since they are pretty self-explanatory if you have a cursory look at the grammar.

So, what are we waiting for? Let's start writing our little codebase that will parse this query string and translate it to an Azure DocumentDB SQL that we can use to fetch the tweets. For that, we need a small repository that will connect to our desired database and collection in DocumentDB and will let us fetch some items. I only added methods that will allow us to read the tweets and connect to the database. I ignored the rest since you can always have a look at those in the quick start for azure document db.

Here's our small rough database repository. Please remember to keep your endpoint and key strings somewhere secret and safe in production environment. Since this is a tutorial, I went with what is easy and fast to go for a proof of concept. 
  1. namespace TweetQuery.Lib  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.Threading.Tasks;  
  6.     using Microsoft.Azure.Documents.Client;  
  7.     using Microsoft.Azure.Documents.Linq;  
  8.   
  9.     public class CosmosDBRepository<T> where T : class  
  10.     {  
  11.         private readonly string Endpoint = "https://tweet.documents.azure.com:443/";  
  12.         private readonly string Key = "fjp9Z3qKPxSOfE0KS1aaKvUY27B8IoL347sdtMBMjkCQqPmoaKjGXoyltrItNXNN6h4QjAYLSY5nyb2djWWUOQ==";  
  13.         private readonly string DatabaseId = "tweetdb";  
  14.         private readonly string CollectionId = "tweets";  
  15.         private DocumentClient client;  
  16.   
  17.         public CosmosDBRepository()  
  18.         {  
  19.             client = new DocumentClient(new Uri(Endpoint), Key);  
  20.         }  
  21.   
  22.         public async Task<IEnumerable<T>> GetItemsAsync(string sql)  
  23.         {  
  24.             if (string.IsNullOrEmpty(sql))  
  25.                 throw new ArgumentNullException(nameof(sql));  
  26.   
  27.             FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };  
  28.   
  29.             var query = this.client.CreateDocumentQuery<T>(  
  30.                  UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),  
  31.                  sql, queryOptions)  
  32.                  .AsDocumentQuery();  
  33.   
  34.             List<T> results = new List<T>();  
  35.             while (query.HasMoreResults)  
  36.             {  
  37.                 results.AddRange(await query.ExecuteNextAsync<T>());  
  38.             }  
  39.   
  40.             return results;  
  41.         }  
  42.     }  
  43. }   

I opted for executing an SQL query instead of a LINQ expression because constructing SQL is easier and simpler for a tutorial. Additionally, it decouples the query structure from compile time POCOs that we use as our models too.

I created a DocumentDbListener class based on the SearchBaseListener which was auto-generated from our ANTLR grammar. The sole purpose of this class is to generate a simple SQL against our search expression. To search inside nested arrays, I used a user defined function for azure document db. All of these are very crudely written, so forgive my indecency. Since this is just a tutorial, I tried to keep it as simple as possible.

  1. function matchArrayElement(array, match) {   
  2.     if (!Array.isArray(array)) return false;  
  3.       
  4.     for (var index = 0; index < array.length; index++) {  
  5.         var element = array[index];  
  6.   
  7.         if (typeof match === "object") {  
  8.             for (var key in match) {  
  9.                 if (match.hasOwnProperty(key) && element.hasOwnProperty(key)) {  
  10.                     var matchVal = match[key];  
  11.                     var elemVal = element[key];  
  12.   
  13.                     return matchVal == elemVal;  
  14.                 }  
  15.             }  
  16.         }  
  17.         else {  
  18.             return (element == match)  
  19.         }  
  20.     }  
  21.   
  22.     return false;  
  23. }   
All this method does is it tries to find nested array elements based on the match we send back. You can achieve the same result thorough JOINs in Azure DocumentDB or Array method ARRAY_CONTAINS, but I preferred a user defined function since it serves my purpose easily.

Constructing SQL from the query expression

To understand how the SQL is generated from the query expression, let's begin with the to:UserAccount expression. Since we start with the rule expr, let's override the SearchBaseListener method EnterExpr first.

  1. namespace TweetSearch.CosmosDb.DocumentDb  
  2. {  
  3.     using Antlr4.Runtime.Misc;  
  4.     using TweetSearch.CosmosDb.Util;  
  5.   
  6.     public class DocumentDbListener : SearchBaseListener  
  7.     {  
  8.         private string projectionClause = "SELECT * FROM twt";  
  9.         private string whereClause;  
  10.   
  11.         public string Output  
  12.         {  
  13.             get { return projectionClause + " " + whereClause; }  
  14.         }  
  15.   
  16.         public override void EnterExpr([NotNull] SearchParser.ExprContext context)  
  17.         {  
  18.             this.whereClause = "WHERE";  
  19.         }  
  20.     }  
  21. }  

The approach I took here is essentially the simplest. I handle the events fired the moment ANTLR enters a specific rule and I keep appending the SQL string to the whereClause. Since, entering the expr rule means that I will need a where SQL clause, I initialized it with "WHERE". The thing to notice here is instead of concatenating I chose to initialize it because I expect this event to be fired exactly once since that is how the grammar is designed.

Following the same trail the next thing to handle will be the EnterTerm event. But, term is nothing but an OR relationship between 4 other rules. Handling them specifically gives me the edge since they produce simpler and smaller readable methods. For example, if we want to handle the to:UserAccount expression, a simple method like following should be sufficient for our use case.

  1. public override void EnterToText([NotNull] SearchParser.ToTextContext context)  
  2. {  
  3.     var screenName = context.GetText().Substring(3).Enquote();  
  4.     this.whereClause = string.Concat(whereClause, " ", $"udf.matchArrayElement(twt.entities.user_mentions, {{ \"screen_name\" : {screenName} }} )");  
  5. }  

This is where our user defined function also comes in play though. I'm trying to find any tweet that has an user mention to the parsed user account I fetched from the query.

By following the same rule I completed the rest of the four rules and my full listener class looks like,

  1. namespace TweetSearch.CosmosDb.DocumentDb  
  2. {  
  3.     using Antlr4.Runtime.Misc;  
  4.     using TweetSearch.CosmosDb.Util;  
  5.   
  6.     public class DocumentDbListener : SearchBaseListener  
  7.     {  
  8.         private string projectionClause = "SELECT * FROM twt";  
  9.         private string whereClause;  
  10.   
  11.         public string Output  
  12.         {  
  13.             get { return projectionClause + " " + whereClause; }  
  14.         }  
  15.   
  16.         public override void EnterExpr([NotNull] SearchParser.ExprContext context)  
  17.         {  
  18.             this.whereClause = "WHERE";  
  19.         }  
  20.   
  21.         public override void EnterFromText([NotNull] SearchParser.FromTextContext context)  
  22.         {  
  23.             var screenName = context.GetText().Substring(5).Enquote();  
  24.             this.whereClause = string.Concat(whereClause, " ""twt.user.screen_name = ", screenName);  
  25.         }  
  26.   
  27.         public override void EnterOp([NotNull] SearchParser.OpContext context)  
  28.         {  
  29.             var text = context.GetText();  
  30.             this.whereClause = string.Concat(this.whereClause, " ", text.ToUpper());  
  31.         }  
  32.   
  33.         public override void EnterToText([NotNull] SearchParser.ToTextContext context)  
  34.         {  
  35.             var screenName = context.GetText().Substring(3).Enquote();  
  36.             this.whereClause = string.Concat(whereClause, " ", $"udf.matchArrayElement(twt.entities.user_mentions, {{ \"screen_name\" : {screenName} }} )");  
  37.         }  
  38.   
  39.         public override void EnterHashText([NotNull] SearchParser.HashTextContext context)  
  40.         {  
  41.             var hashtag = context.GetText().Enquote();  
  42.             this.whereClause = string.Concat(whereClause, " ", $"udf.matchArrayElement(twt.entities.hashtags, {hashtag})");  
  43.         }  
  44.   
  45.         public override void EnterExactText([NotNull] SearchParser.ExactTextContext context)  
  46.         {  
  47.             var text = context.GetText();  
  48.             this.whereClause = string.Concat(whereClause, " ", $"CONTAINS(twt.text, {text})");  
  49.         }  
  50.     }  
  51. }  
We got our listener ready! Now, all we need is a context class that will bootstrap the lexer and parser and tokens so the input expression is transpiled and the output SQL is generated. Just like our last work on ANTLR, the TweetQueryContext class will look like the following,
  1. namespace TweetSearch.CosmosDb.DocumentDb  
  2. {  
  3.     using Antlr4.Runtime;  
  4.     using Antlr4.Runtime.Tree;  
  5.   
  6.     public class TweetQueryContext  
  7.     {  
  8.         private DocumentDbListener listener;  
  9.   
  10.         public TweetQueryContext()  
  11.         {  
  12.             this.listener = new DocumentDbListener();  
  13.         }  
  14.   
  15.         public SearchParser.ExprContext GenerateAST(string input)  
  16.         {  
  17.             var inputStream = new AntlrInputStream(input);  
  18.             var lexer = new SearchLexer(inputStream);  
  19.             var tokens = new CommonTokenStream(lexer);  
  20.             var parser = new SearchParser(tokens);  
  21.             parser.ErrorHandler = new BailErrorStrategy();  
  22.   
  23.             return parser.expr();  
  24.         }  
  25.   
  26.         public string GenerateQuery(string inputText)  
  27.         {  
  28.             var astree = this.GenerateAST(inputText);  
  29.             ParseTreeWalker.Default.Walk(listener, astree);  
  30.             return listener.Output;  
  31.         }  
  32.     }  
  33. }  

Whew! That was easy, right?

Bootstrapping the api layer

We have all we need except the api. Thanks to asp .net core, that is two clicks away. Open Visual Studio and open a .net core api project. Our TweetsController class looks like the following,

  1. namespace TweetQuery.Controllers  
  2. {  
  3.     using Microsoft.AspNetCore.Mvc;  
  4.     using System.Threading.Tasks;  
  5.     using TweetQuery.Lib;  
  6.     using TweetQuery.Lib.Model;  
  7.     using TweetSearch.CosmosDb.DocumentDb;  
  8.   
  9.     [Route("api/[controller]")]  
  10.     public class TweetsController : Controller  
  11.     {  
  12.         private CosmosDBRepository<Tweet> repository;  
  13.         private TweetQueryContext context;  
  14.   
  15.         public TweetsController(CosmosDBRepository<Tweet> repository)  
  16.         {  
  17.             this.repository = repository;  
  18.             this.context = new TweetQueryContext();  
  19.         }  
  20.   
  21.         [HttpGet("search")]  
  22.         public async Task<IActionResult> Search([FromQuery] string q)  
  23.         {  
  24.             if (string.IsNullOrEmpty(q))  
  25.                 return BadRequest();  
  26.   
  27.             var querySql = this.context.GenerateQuery(q).Trim();  
  28.             var result = await repository.GetItemsAsync(querySql);  
  29.             return Ok(result);  
  30.         }  
  31.     }  
  32. }  

I reused the db repository we created earlier and as you see that is dependency injected in the controller which you have to configure in the ConfigureServices method in your Startup class. I'm not adding that specific code here since it is already in the sample code and doesn't belong to the scope of this tutorial. Same goes for the model class Tweet and the classes it uses inside.

Time to test!

The project is hosted here in github. I also attached it with this article. Clone or download the code from here. Build and run it from your visual studio. As a sample query try the following:

  1. http://localhost:5000/api/tweets/search?q=to:hatena_sugoi AND from:maeta_tw OR %23HopesUp OR "Surely June is a summer"  

I url-encoded the hashtag here just to be nice on the REST client you might use. I highly suggest Postman if you don't want anything heavy.

I only took the minimalists way of using ANTLR here, you can build your own expression tree based on the auto-generated listener and can do so much more if you want.

I hope this was fun. Happy RESTing!


Similar Articles