Skip to main content

First Class SQL for Full Text Search

Icons made by Freepik from www.flaticon.com

(With SQL) Your app is sitting on a Ferrari-style compute engine.  
— Lukas Eder

Over time, the database industry has realized text search and SQL are two sides of the same coin. Text search needs further query processing, query processing needs text search to efficiently filter for text patterns. The SQL databases have added text search within them, albeit for a single node SMP systems.

Couchbase Full-Text Search (FTS) is created with three main motivations:

  • Transparently search across multiple fields within a document
  • Go beyond the exact matching of values by providing language based stemming, fuzzy matching, etc.
  • Provide the search results based on relevance

FTS achieves this on an inverted index and a rich set of query predicates : from simple word search to pattern matching to complex range predicates. In addition to the search, it supports aggregation via search facets .

In the NoSQL world, Lucene is a popular search index and so are the search servers based on Lucene: all have added SQL for their search. Couchbase introduced the full text service, Solr and Elasticsearch. Following their RDBMS cousins, ElasticsearchOpendistro for Elasticsearch FTS and has followed up with support for search within N1QL.

The SQL Implementations of Elasticsearch with SQL and MongoDB's MQL comes with a long list of limitations.

Elasticsearch with SQL has listed its limitations here:

MongoDB's MQL's search integration comes with a long list of limitations.

  • Available only on the Atlas search service, not on the on-prem product.
  • Search can only be the FIRST operation within the aggregate() pipeline.
  • Available only within the aggregation pipeline (aggregate()) and not in find(), insert(), update(), remove() other other operations.

The integration with its aggregate() API, comes with some limitations: It can only be the first operation in the pipeline unavailable on its on-prem database. The features we discuss in this article are in Couchbase 6.5 and above.

Here's an example from N1QL:

SQL
1
SELECT country, 
2
               city, 
3
               name, 
4
               ROW_NUMBER() OVER(ORDER BY country DESC, city DESC) rownum
5
FROM `travel-sample` AS t1
6
WHERE t1.type = "hotel" AND SEARCH(t1.description, "garden") 
7
AND ANY r in reviews satisfies r.ratings.Service > 3 END;



This includes the following in addition to SEARCH():

  • Projection of fields from the documents: country, city, name
  • Row number generation via the window function ROW_NUMBER()
  • Additional scalar predicate t1.type = "hotel"
  • Array predicate on reviews (ANY)

You get the FULL benefit of first-class query processing in addition to efficient search. That's not all - there's even more with N1QL. The benefits and effectiveness of SQL  are well known. N1QL is SQL for JSON. The goal of N1QL is to give developers and enterprises an expressive, powerful, and complete language for querying, transforming, and manipulating JSON data.

The benefits of using with the search are the following:

  1. Predicates:
    • FTS is great with searching based on relevance. SQL is great with additional complex query processing: complex predicates, array predicates, additional scalar
  2. JOIN processing
    1. N1QL can do INNER JOIN, LEFT OUTER JOIN, (limited) RIGHT OUTER JOIN, NEST, UNNEST
    2. JOINS between buckets, collections and results of subqueries.
  3. More than SEARCH()
    1. In addition to SELECT, you can use SEARCH() predicate in the WHERE clauses of INSERT, UPDATE, DELETE, MERGE statements.
    2. You can PREPARE these statements and EXECUTE them repeatedly and efficiently.
    3. You get the usual security via the RBAC roles via GRANT & REVOKE.
  4. Developer productivity: Write the query in SQL, the language they already know.

Let's Look at how the N1QL engine executes this. Abhinav Dangeti from the Couchbase FTS engineering has already written a great blog detailing the decision making and examples. This article is to explain this visually with additional examples in the categories mentioned above.

1. Architecture for Query Execution

We've added three important steps to query execution the query uses SEARCH() :

  1. The planner considers the FTS search index one of the valid access paths if search() predicate exists in the query.
    • If the search index is selected, then it creates the plan by pushing down the search predicate to the FTS index.
  2. When the search index is selected, executor issues the search request to one of the FTS nodes (instead of the scan request to the index service)
  3. Before the results from the search are finalized, the query service re-verifies the search qualification of the document to the data.


2. Predicate Processing

In the following query, the SEARCH() predicate (predicate-2) is pushed to the FTS search request. Every other predicate is processed by the query engine post search in the "Filter" phase - as shown in the "Inside a Query Service" figure above. This is one exception to this. When the FTS index has created an index with JSON type field (doc_config.type_field in the index definition document) is defined (in this case type = "hotel") to create the index on the subset of the document, both index selection and search pushdown exploits this predicate. Even in this case, the predicate is re-applied after the document fetch.

SQL
1
SELECT country, 
2
               city, 
3
               name, 
4
               ROW_NUMBER() OVER(ORDER BY country DESC, city DESC) rownum
5
FROM `travel-sample` AS t1
6
WHERE 
7
t1.type = "hotel"   /* predicate-1 */
8
AND SEARCH(t1.description, "garden") /* predicate-2 */
9
AND ANY r in reviews satisfies r.ratings.Service > 3 END; /* predicate-2 */



Here's an example of a query exploiting the operators and functions.

SQL
1
SELECT LOWER(country),   /* scalar function */
2
       city, 
3
       lastname || " " || firstname AS fullname   /* string operator */
4
       ROW_NUMBER() OVER(ORDER BY country DESC, city DESC) rownum   /* window function */
5
FROM `travel-sample` AS t1
6
WHERE 
7
LOWER(t1.type) = "hotel"   /* scalar function */
8
AND SEARCH(t1.description, "garden") 
9
AND ARRAY_CONTAINS(public_likes, "Joe Black")  /* Array function */



Here's the query plan for this query. IndexSearch does the FTS search request and this is layered into the query execution pipeline. Hence the query gets the benefit of all the other capabilities of N1QL. This reflects the pipeline stages in the figure above.

4. JOIN Processing

.The SEARCH() can also be used as part of the join processing. In this case, the FTS is used to find all the cities which have hotels with gardens and then join with airports.

SQL
1
SELECT hotel.name hname,
2
       airport.city
3
FROM `travel-sample` hotel 
4
LEFT OUTER JOIN `travel-sample` airport ON hotel.city = airport.city
5
WHERE hotel.type = 'hotel'
6
    AND SEARCH(hotel.description, "garden")
7
    AND airport.type = 'airport' ;





N1QL in query service supports non-recursive CTEs. You can use SEARCH() within each expression. The derived table from that expression (hotel and airport) are used as keyspaces within the query.

SQL

1
WITH hotel AS (
2
    SELECT name,
3
           city
4
    FROM `travel-sample`
5
    WHERE type = 'hotel'
6
        AND search(description, "garden")),
7
airport AS (
8
    SELECT name,
9
           city
10
    FROM `travel-sample`
11
    WHERE type = 'airport'
12
        AND SEARCH(city, "angeles"))
13
SELECT hotel.name hname,
14
       airport.city
15
FROM hotel
16
INNER JOIN airport ON hotel.city = airport.city
17
ORDER BY airport.city,
18
         hotel.name;



5. Use in UPDATEs

SEARCH() can be used anywhere a predicate is allowed within other DML statements.

SQL

1
/* INSERT INTO... SELECT statement. */
2
INSERT INTO mybucket (KEY id, VALUES v)
3
          SELECT meta().id  id, v 
4
          FROM `travel-sample` v
5
          WHERE SEARCH(v, "+type:hotel  +description:clean");
6
 
7
/* DELETE statement */
8
DELETE FROM `travel-sample` WHERE SEARCH(v, "+type:hotel +description:clean");
9
 
10
/* UPDATE statement */
11
UPDATE `travel-sample` SET new_field = "search n update!" WHERE SEARCH(v, "+type:hotel +description:clean"); 
12
 



The examples can flow a long time. I've shown common sample examples. You use this in various SQL statements (DMLs)

Conclusion

Couchbase FTS provides a scalable, distributed text search engine. We've seamlessly layered it into N1QL in Couchbase Query service so you get the full power of queries with the full power of search. There's more innovation on this in the pipeline. Stay tuned!

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 ...