How to Use Elasticsearch for Full-Text Search: A Step-by-Step Tutorial
Elasticsearch is a distributed, RESTful search engine built on Apache Lucene. It excels at full-text search by indexing documents and returning highly relevant results in milliseconds. This tutorial covers the essentials: setting up an index, indexing data, and running search queries.
Elasticsearch organizes data into indices (similar to databases) and documents (similar to rows). Each document has fields with defined data types. For full-text search, fields should use the text type (which is analyzed) rather than keyword (exact match). You define this in a mapping.
1. Create an Index and Add Documents
Use the Index API to create an index and push documents. Here’s an example using curl:
- Create the index (with mapping):
PUT /articleswith mapping defining"content": {"type": "text"}. - Index a document:
POST /articles/_doc/1 {"title": "Elasticsearch guide", "content": "Learn how to search and analyze..."} - Repeat for multiple documents to build your corpus.
2. Perform Full-Text Searches with match Query
The match query analyzes your input and searches for relevant documents. Example:
GET /articles/_search with body {"query": {"match": {"content": "search guide"}}}.
Elasticsearch returns results ranked by relevance score (_score).
3. Boost Relevancy with Field Boosting
You can prioritize certain fields (e.g., title over body) using the multi_match query:
{"query": {"multi_match": {"query": "search", "fields": ["title^3", "content"]}}}
The ^3 multiplies the title field score by 3, making titles more influential.
4. Refine with Phrase and Fuzzy Matching
Use match_phrase for exact phrases: {"match_phrase": {"content": "full text search"}}. For typo tolerance, add "fuzziness": "AUTO" to your match query.
Conclusion
Elasticsearch provides a powerful, scalable full-text search solution. Start with simple match queries, then layer on boosting, phrase matching, and fuzzy search to fine-tune results. Explore the official documentation for more advanced features like aggregations and custom analyzers.