DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Control Your Services With OTEL, Jaeger, and Prometheus
  • Implementing LSM Trees in Golang: A Comprehensive Guide
  • Keeping Two Multi-Master Databases Aligned With a Vector Clock
  • Pivoting Database Systems Practices to AI: Create Efficient Development and Maintenance Practices With Generative AI

Trending

  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Memory Leak Due to Time-Taking finalize() Method
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Caching 101: Theory, Algorithms, Tools, and Best Practices
  1. DZone
  2. Data Engineering
  3. Data
  4. A Couchbase Index Technique for LIKE Predicates With Wildcard

A Couchbase Index Technique for LIKE Predicates With Wildcard

Take a look at some of the latest changes to Couchbase in action, including a more efficient way to index and query your data.

By 
Tai Tran user avatar
Tai Tran
·
Sep. 20, 16 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
10.9K Views

Join the DZone community and get the full member experience.

Join For Free

I have a query below where I want to find all documents in the travel-sample bucket having the airport name containing the string “Washington.”

SELECT airportname from `travel-sample`
where
    airportname LIKE "%Washington%"
AND type = "airport"


This is a classic problem with most of the RDBMS systems where these systems can't use the index when a LIKE predicate has a leading wildcard i.e. leading %. Elsewhere in this article, I will refer to the query above as the "slow query." I am pleased to tell you that help is on the way with Couchbase release 4.5.1, where this problem can be solved with a combination of the new SUFFIXES() function and Array Index. 

Note: To follow along with the examples in this article, please refer to the setup instructions as given here to install the travel-sample Couchbase bucket.

SUFFIXES() is a N1QL function that generates all suffixes of an input string. For example, the N1QL statement below:

select SUFFIXES("Baltimore Washington Intl") 


That returns an array of suffixes:

[
      "Baltimore Washington Intl",
      "altimore Washington Intl",
      "ltimore Washington Intl",
      "timore Washington Intl",
      "imore Washington Intl",
      "more Washington Intl",
      "ore Washington Intl",
      "re Washington Intl",
      "e Washington Intl",
      " Washington Intl",
      "Washington Intl",
      "ashington Intl",
      "shington Intl",
      "hington Intl",
      "ington Intl",
      "ngton Intl",
      "gton Intl",
      "ton Intl",
      "on Intl",
      "n Intl",
      " Intl",
      "Intl",
      "ntl",
      "tl",
      "l"
    ]


By applying the SUFFIXES() function on the airportname attribute of the documents of type 'airport,' Couchbase generates an array of suffixes for each document. You can then create an array index on the suffixes arrays and rewrite the query to leverage such index. Here is an example:

  • Create an array index on the suffixes of the airportname attribute :
create index suffixes_airport_name on `travel-sample`(
       DISTINCT ARRAY array_element FOR array_element IN SUFFIXES(LOWER(airportname)) END)
       WHERE type = "airport";


  • The "slow query" can be rewritten to use the suffixes_airport_name index and returns all the documents containing the airportname suffix, starting with 'washington%.' It is worth noting that in this re-written query the LIKE predicate no longer needs the leading % wildcard because the matching criterion is on the suffixes.
select airportname from `travel-sample`
where
    ANY array_element IN SUFFIXES(LOWER(airportname)) SATISFIES array_element LIKE 'washington%' END
and  type="airport";

the query returns
[
  {
    "airportname": "Ronald Reagan Washington Natl"
  },
  {
    "airportname": "Washington Dulles Intl"
  },
  {
    "airportname": "Baltimore Washington Intl"
  },
  {
    "airportname": "Washington Union Station"
  }
]


The elapsed time for this rewritten query is roughly 25ms when executed on my small VM cluster, and it is 10 times faster compared to the elapsed time of the original "slow query." I am including a portion of the explain plan to confirm that the rewritten query uses the array index. 

[
  {
        ...
            {
              "#operator": "DistinctScan",
              "scan": {
                "#operator": "IndexScan",
                "index": "suffixes_airport_name",
                "index_id": "6fc9785d59a93892",
                "keyspace": "travel-sample",
                "namespace": "default",
                "spans": [
                  {
                    "Range": {
                      "High": [
                        "\"washingtoo\""
                      ],
                      "Inclusion": 1,
                      "Low": [
                        "\"washington\""
                      ]
                    }
                  }
                ],
                "using": "gsi"
              }
            }
        ......
]


A common application of such a query is when an end user enters a partial searching string in a UI search field, e.g. searching for an airport name. After the end user has entered a few characters, the logic behind the search field issues the query and displays the matches returned as a drop-down picklist (much like what you see when you enter search terms in Google).  

Readers should be aware that the longer the input string, the longer the list of suffixes and, therefore, the index on suffixes can be large.  I recommend using this technique only on short attributes, which belong to small Reference Data collections, such as Airport, Hotel, Product Catalog, etc. 

If your documents have multi-value attribute(s) such as SKILLS, TAGS as shown in the sample document below, I recommend using the SPLIT() function instead of SUFFIXES().

candidate: {
        name: "John Doe",
        skills: "JAVA,C,NodeJS,SQL",
}


Below is a simple example of SPLIT(). When it is invoked with an input string of comma-separated words, it will return an array of words. 

SELECT SPLIT("JAVA,C,NodeJS,SQL", ",")

The select returns:

[
  {
    "$1": [
      "JAVA",
      "C",
      "NodeJS",
      "SQL"
    ]
  }
]


By creating an array index on these arrays of words, your application should be able to support word search. You should try this out yourself to see how it works.

If you have documents with long text attributes such as "Description", TOKENS() function is more suitable for parsing text paragraphs into individual words. The TOKENS() function is not available in our current GA release but will be soon.

Database Data structure

Opinions expressed by DZone contributors are their own.

Related

  • Control Your Services With OTEL, Jaeger, and Prometheus
  • Implementing LSM Trees in Golang: A Comprehensive Guide
  • Keeping Two Multi-Master Databases Aligned With a Vector Clock
  • Pivoting Database Systems Practices to AI: Create Efficient Development and Maintenance Practices With Generative AI

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!