Skip to main content

Flexible Query and Indexing for Flexible JSON Model

 


Use N1QL when you're in a JSON pickle. - Confucius

For the JSON data model, the general advice is to think of collections as tables, JSON documents as denormalized rows, and field names as columns — roughly. All this holds true in databases like Couchbase and MongoDB when recommendations are strictly followed. There are many reasons why users don't simply follow this key-value pair model all the time. Here are the main reasons:

  1. You want to convert a map/hashmap data structure where the keys are dynamic.

  2. Timeseries data when the field names are usually encoded timestamps.

  3. Dictionary based encoding.

  4. Existing document formats and standards disallow redesign.

If your database and query language the query language doesn't deal with the situation, you've to go through an elaborate redesign. In addition to simply accessing the information, how do you make the queries on JSON efficient when you don't even know the name of the field you have to index on? Fortunately, Couchbase N1QL has a variety of query and index features to deal with flexible metadata as well.

Let's consider these use cases.

Use Case 1: Value Transformation

Here's a sample JSON document.

JSON


The JSON data model is described simply as a set of key-value pairs. Each key is a string, unique at that its level of the hierarchy and value can be scalars, objects, or arrays. A rigorous definition can be read. JSON is also self-describing, and that makes it flexible for a database document model . Not every customer has to have a fixed number of telephone numbers or cars or any other type of attributes.

The same information above can be reorganized, as the JSON below without any loss of information, but some implicit schema.

JSON


This is all well and good if you're simply putting and setting the document. It doesn't matter what the structure of JSON is. Simply schlep it back and forth.

Now, let's see how this affects querying.

SQL


With the new JSON model, there isn't a field name called, cxname, here.

SQL


What is the magic of the object_pairs() function? This transforms the JSON {"key":"value"} pairs into an array of name-value pairs. Here's an example.

SQL


The OBJECT_NAMES() function extracts the key (here "Jane Smith") and returns it as a value, which then can be indexed at. Since the function returns not just one value, but an array of "key names" as values, you need to create an array index. Queries Q1 and Q2 do the same job for the respective data model. But, we need each of those queries to execute in milliseconds.

For Q1, we simply create the index on cxname.

SQL


For Q2:

SQL


With this index, for Q2, you'll get a plan that uses the index.

JSON


Use Case 2: Dynamic Key Names

This is use case is taken from the Couchbase forum post.

JSON


Question: What would be the best way to index the values within translations dynamically? I.e. a generic index that indexes all keys within the translations object.

If the need is to simply query for English documents all the time, to query all documents that have translations.en = "Hello".

If you're always looking for translations to English, you can simply create the index on transactions.en.

SQL


If the keys are dynamic, you don't know what specific language is going to be in the data and which ones can be queries upon. You have to make them both dynamic.

SQL


Here's the explanation to verify that the index is indeed picked up and the predicates are pushed down to the index scan.

JSON


Not to worry, if the index definition looks a bit more complicated than normal. The Index Advisor has you covered.

SQL


You can even add expressions on top of each expression you're evaluating.

SQL


More Object Functions

N1QL has additional object and nested data functions to help with complex data models. Check out the full set of object functions and the token functions.

References:
  1. Couchbae N1QL Object Functions Documentation.
  2. Couchbase Array indexing.
  3. Couchbase index blog.

Comments

Popular posts from this blog

Swami Vivekananda: The Monk That Nobody Sent to Chicago

  There’s a saying in Chicago: “We don’t want nobody that nobody sent.” This was the cold reception Swami Vivekananda faced when he arrived in the windy city in July 1893, determined to attend the World Parliament of Religions that September. He belonged to no organization, carried no letter of recommendation, his countrymen were nobody, and represented an alien religion to the Western world. As the days passed, his hope of attending the parliament dwindled. With money running out and the odds stacked against him, he left the Windy City and went to Boston, praying for a glimmer of opportunity.  Swamiji came to America to share India’s most profound gift: the wisdom of the Hindu sages, preserved through centuries of oral tradition and embodied by its monks. This was 1893, not 1993—India was under the British grip, its resources drained, and its spirit subdued. Swamiji’s mission was not just a cultural exchange; it was a bold step toward envisioning a future where India could re...

Why Should Databases Go Natural?

From search to CRM, applications are adopting natural language and intuitive interactions. Should databases follow? This article provides a strategic perspective. Amid the many technological evolutions in software and hardware (CISC/RISC, Internet, Cloud, and AI), one technology has endured:  Relational Database Systems   (RDBMS), aka SQL databases. For over 50 years, RDBMS has survived and thrived, overcoming many challenges. It has evolved and adopted beneficial features from emerging technologies like object-relational databases and now competes robustly with   NoSQL databases .  Today, RDBMS dominates the market, with four of the top five databases and seven of the top ten being relational. RDBMS has smartly borrowed ideas, like JSON support, from NoSQL, while NoSQL has also borrowed from RDBMS. NoSQL no longer rejects SQL. From a user perspective, all modern databases have SQL-inspired query language and a set of APIs. All applications manage the respective data...

iQ Interactive: Cool Things for Developers on Couchbase Capella iQ

  The landscape of software development is ever-evolving with the advent of new technologies. As we venture into 2023, natural language processing ( NLP ) is rapidly emerging as a pivotal aspect of programming. Unlike previous generations of tools that primarily aimed at enhancing coding productivity and code quality, the new generation of Artificial Intelligence ( GenAI ) tools, like iQ, is set to revolutionize every facet of a developer's workflow. This encompasses a wide range of activities: Reading, writing, and rewriting specifications Designing, prototyping, and coding Reviewing, refactoring, and verifying software Going through the iterative cycle of deploying, debugging, and improving the software Create a draft schema and sample data for any use case Natural language queries. Generate sample queries on a given dataset Fix the syntax error for a query Don't stop here. Let your imagination fly. Although the insights garnered from iQ are preliminary and should be treated ...