애플리케이션 디자인

Typeahead: Develop with Couchbase Full-Text Search & Node.js

Over the past year or so I’ve written a variety of tutorials around the full-text search (FTS) service of Couchbase, most of which are specific examples of how to do something with one of the SDKs and never really anything to do with the application behind it. One of many possible realistic applications includes using a typeahead or data suggestion feature in a web application form. Based on user input, possible results are searched against and displayed.

We’re going to see how to build a typeahead form using the full-text search service in 카우치베이스, Node.js, and jQuery to string it all together.

Before getting too involved, the assumption is that you already have Couchbase Server 5.0+ installed and configured with full-text search enabled. The assumption is that you already have Node.js installed as well because the API will be powered with Node.js and Express Framework.

Creating a NoSQL Dataset with FTS Indexes

When working with FTS, you could be using one of a potentially unlimited number of searching scenarios. We’re going to be a little more specific for the purpose of this example.

Let’s assume that we are working with music data and our goal is to search for songs based on artist, album, or song title. Let’s assume that each of our NoSQL documents takes the following format:

Not the most complex JSON document, but it could be if we wanted it to be. For the sake of this example, we’re just going to worry about the title 그리고 artist, even though it wouldn’t take much more effort to expand.

To use FTS, we’re going to need to create a special index in Couchbase that looks like the following:

To summarize, we need to come up with a name for the index, specify the type mapping, and define the fields that will be indexed, all of which will be stored in the index itself.

When creating the index, it is important to store the field, otherwise, we won’t have anything to display in our typeahead.

Developing a Node.js RESTful API Endpoint for Searching

Now that we have some data in the database and an index created for searching, we can create an API endpoint with Node.js. The point of this API is to act as an endpoint for our search form to use. After all, we wouldn’t want our client-facing frontend to hit the database directly as that would be unsafe.

On your computer, create a new project and execute the following from the command line:

The above commands will create a new package.json file and install the few dependencies of our project. We’ll be using the Couchbase SDK with Express Framework and we’re installing a package to handle cross-origin resource sharing (CORS).

Because our application is small, let’s create an app.js file in our project to contain all of our code. We can bootstrap it with the following:

In the above code, we’ve imported our downloaded dependencies, configured Express and connected them to our Couchbase instance. You’ll need to swap out the connection information with that of your actual database instance.

/search endpoint is where all the magic is going to happen. Let’s dig into it:

First, we define our query as a match query against our particular index. The match query will use whatever text is passed in via the query parameters of the request. We’re also going to be using a fuzzy search with a value of 1 to accommodate misspellings of words.

Before we execute the query, we define that we want the title 그리고 artist back in the results. These are the same fields we added to our index.

Upon successful execution of the query, we parse our results to only return what we want, rather than the extra metadata that comes back with the response.

Using a cURL request, you could hit https://localhost:3000/search?query=swift and see various results depending on your dataset.

Designing a Frontend with jQuery and Typeahead libraries

Searching with cURL has its values, but most of the time it isn’t what we’re going to want to do. Instead, we should create a client-facing front end using readily available web technologies.

There are a lot of potential libraries out there, but we’re going to use typeahead.js which maintained by Twitter. You’ll need to download it, but take note that we’re going to be using version 0.10.5 of the library due to bugs in the latest. I wasted a good portion of the day trying to troubleshoot the library only to find this out.

Create a project that contains the following structure:

Yes, you will need Handlebars.js 그리고 jQuery to be successful with this frontend. As far as I know, the version doesn’t matter, we just care about the version of our typeahead library.

Within the project’s 인덱스.html file, include the following:

Ignoring how we’ve just done basic HTML markup to include our styles and scripts, jump ahead into our typeahead function. For the configuration, we’re going to show popup hints for any records found, require that at least 3 characters are present, don’t highlight matching words, and limit our results to 5 items displaying. Feel free to adjust the settings to your specifications.

In the next section, we define our displayKey. We know that we’re getting an array of objects back and an 아이디 is one of the properties of those objects. We want that value to show in our form after selection. For the data source, we are doing a GET request to our API endpoint and passing the response back to our typeahead library. Everything will be rendered in the 템플릿 area.

결론

You just saw how to use a typeahead, often referred to as autosuggestions or auto-complete, using jQuery, Node.js, and full-text search (FTS) in Couchbase. There are many use cases when it comes to full-text search and many different libraries available for typeahead functionality. This tutorial is more or less for giving you an idea for the future.

For more information on using Couchbase with Node.js, check out the 카우치베이스 개발자 포털.

이 기사 공유하기

작가

닉 라보이(Nic Raboy)는 모던 웹 및 모바일 개발 기술의 옹호자입니다. 그는 자바, 자바스크립트, 골랑(Golang)을 비롯해 앵귤러, 네이티브스크립트, 아파치 코르도바 같은 다양한 프레임워크 경험을 가지고 있습니다. 닉은 웹 및 모바일 개발을 더 쉽게 이해할 수 있도록 돕는 자신의 개발 경험에 대해 글을 씁니다.

댓글 남기기

카우치베이스 카펠라를 시작할 준비가 되셨나요?

개발 시작하기

NoSQL을 탐색하고, 리소스를 찾아보고, 튜토리얼을 시작하려면 개발자 포털을 확인하세요.

카펠라 프리 사용하기

단 몇 번의 클릭으로 카우치베이스(Couchbase)를 직접 체험해 보세요. Capella DBaaS는 시작하기 가장 쉽고 빠른 방법입니다.

연락해

Couchbase 제품군에 대해 더 알고 싶으신가요? 저희가 도와드리겠습니다.