mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+417
-270
@@ -1,272 +1,419 @@
|
||||
---
|
||||
description: This rule provides comprehensive best practices for developing with Elasticsearch, covering code organization, performance, security, testing, and common pitfalls, ensuring efficient and maintainable Elasticsearch applications. These practices apply broadly across languages interacting with Elasticsearch.
|
||||
globs: *.py,*.js,*.java,*.go,*.ts,*.kt,*.scala,*.rb,*.php,*.rs,*.c,*.cpp,*.cs,*.swift,*.m,*.h
|
||||
description: This rule file guides developers on best practices for using Elasticsearch, focusing on data modeling, query optimization, performance, and code structure for robust, high-performance search applications.
|
||||
globs: **/*
|
||||
---
|
||||
- # Elasticsearch Library Best Practices
|
||||
|
||||
This document provides comprehensive guidelines for developing with Elasticsearch, covering code organization, common patterns, performance considerations, security best practices, testing approaches, common pitfalls, and tooling.
|
||||
|
||||
- ## 1. Code Organization and Structure
|
||||
|
||||
- ### Directory Structure
|
||||
|
||||
- **Project Root:** Contains the main application code, configuration files, and build scripts.
|
||||
- **src/:** Source code for your application. This directory is further subdivided:
|
||||
- **config/:** Configuration files for Elasticsearch connections and settings.
|
||||
- **mappings/:** JSON files defining Elasticsearch index mappings.
|
||||
- **queries/:** Stored Elasticsearch queries for reuse.
|
||||
- **models/:** Data models representing Elasticsearch documents.
|
||||
- **utils/:** Utility functions for interacting with Elasticsearch.
|
||||
- **scripts/:** Scripts for indexing, reindexing, and data migration.
|
||||
- **tests/:** Unit and integration tests.
|
||||
- **docs/:** Documentation for your application and Elasticsearch integration.
|
||||
- **data/:** Sample data for testing and development.
|
||||
- **.cursor/:** Stores cursor rule files if using Cursor IDE.
|
||||
|
||||
- ### File Naming Conventions
|
||||
|
||||
- **Configuration Files:** `elasticsearch.config.json`, `index.mapping.json`
|
||||
- **Data Models:** `user.model.js`, `product.model.py`
|
||||
- **Utility Functions:** `elasticsearch.utils.go`, `query_builder.rb`
|
||||
- **Test Files:** `user.model.test.js`, `elasticsearch.utils_test.py`
|
||||
|
||||
- ### Module Organization
|
||||
|
||||
- Divide your code into logical modules, such as:
|
||||
- **elasticsearch_client:** Handles the Elasticsearch client initialization and connection management.
|
||||
- **index_management:** Manages index creation, deletion, and mapping updates.
|
||||
- **query_builder:** Provides functions for building complex Elasticsearch queries.
|
||||
- **data_ingestion:** Handles data ingestion and indexing processes.
|
||||
- **search_service:** Implements the search logic and result processing.
|
||||
|
||||
- ### Component Architecture
|
||||
|
||||
- Use a layered architecture to separate concerns:
|
||||
- **Presentation Layer:** Handles user input and displays search results.
|
||||
- **Application Layer:** Orchestrates the interaction between the presentation and domain layers.
|
||||
- **Domain Layer:** Contains the core business logic and data models.
|
||||
- **Infrastructure Layer:** Provides access to external services like Elasticsearch.
|
||||
|
||||
- ### Code Splitting
|
||||
|
||||
- If your application handles large datasets or complex queries, consider code splitting:
|
||||
- Split large mapping files into smaller, manageable chunks. Use `@file` directives if using Cursor to include them in the primary rule file.
|
||||
- Implement lazy loading for infrequently used features.
|
||||
- Optimize queries to minimize the amount of data transferred.
|
||||
|
||||
- ## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- ### Design Patterns
|
||||
|
||||
- **Repository Pattern:** Abstract data access logic behind a repository interface.
|
||||
- **Factory Pattern:** Create Elasticsearch clients and query builders using factories.
|
||||
- **Builder Pattern:** Construct complex Elasticsearch queries step-by-step.
|
||||
- **Observer Pattern:** Notify subscribers of index updates or data changes.
|
||||
|
||||
- ### Recommended Approaches
|
||||
|
||||
- **Bulk Indexing:** Use the bulk API for efficient indexing of large datasets.
|
||||
- **Scroll API:** Use the scroll API for retrieving large result sets.
|
||||
- **Asynchronous Operations:** Use asynchronous operations for non-blocking Elasticsearch interactions.
|
||||
|
||||
- ### Anti-patterns and Code Smells
|
||||
|
||||
- **Over-sharding:** Avoid creating too many shards, which can lead to performance issues.
|
||||
- **Ignoring Errors:** Always handle Elasticsearch errors and log them appropriately.
|
||||
- **Hardcoding Queries:** Avoid hardcoding queries directly in your code. Use query builders or stored queries.
|
||||
- **Excessive Data Retrieval:** Only retrieve the fields you need from Elasticsearch.
|
||||
|
||||
- ### State Management
|
||||
|
||||
- Keep track of the index state (e.g., creation date, mapping version).
|
||||
- Use version control for index mappings and queries.
|
||||
- Implement rollback mechanisms for data migration.
|
||||
|
||||
- ### Error Handling
|
||||
|
||||
- Use try-except blocks to catch Elasticsearch exceptions.
|
||||
- Log errors with sufficient context for debugging.
|
||||
- Implement retry mechanisms for transient errors.
|
||||
- Implement circuit breaker pattern to prevent cascading failures.
|
||||
|
||||
- ## 3. Performance Considerations
|
||||
|
||||
- ### Optimization Techniques
|
||||
|
||||
- **Mapping Optimization:**
|
||||
- Use the appropriate data types for your fields.
|
||||
- Use `keyword` type for fields that are used for filtering or sorting.
|
||||
- Use `text` type for fields that are used for full-text search.
|
||||
- Disable indexing for fields that are only used for retrieval (`"index": false`).
|
||||
- Consider using `multi-fields` for different types of searches (e.g., keyword and text).
|
||||
- **Query Optimization:**
|
||||
- Use the `filter` context for queries that do not affect scoring.
|
||||
- Use the `bool` query to combine multiple conditions effectively.
|
||||
- Use the `match` query for full-text searches.
|
||||
- Utilize caching mechanisms for frequently executed queries.
|
||||
- **Indexing Optimization:**
|
||||
- Use the bulk API for indexing large amounts of data.
|
||||
- Increase the refresh interval for less frequent updates.
|
||||
- Optimize shard sizes based on your data volume.
|
||||
- Avoid over-sharding.
|
||||
|
||||
- ### Memory Management
|
||||
|
||||
- Monitor the Elasticsearch heap usage.
|
||||
- Configure the JVM heap size appropriately.
|
||||
- Avoid memory leaks in your application code.
|
||||
|
||||
- ### Rendering Optimization (If Applicable)
|
||||
|
||||
- Implement pagination for large result sets.
|
||||
- Use virtualization techniques for rendering large lists.
|
||||
- Optimize the rendering performance of your UI components.
|
||||
|
||||
- ### Bundle Size Optimization
|
||||
|
||||
- Minimize the size of your application's bundle.
|
||||
- Use code splitting to load only the necessary modules.
|
||||
- Optimize your dependencies and remove unused code.
|
||||
|
||||
- ### Lazy Loading
|
||||
|
||||
- Implement lazy loading for infrequently used features.
|
||||
- Load data on demand as needed.
|
||||
- Use asynchronous operations for loading data.
|
||||
|
||||
- ## 4. Security Best Practices
|
||||
|
||||
- ### Common Vulnerabilities
|
||||
|
||||
- **Injection Attacks:** Prevent injection attacks by validating user input and sanitizing data.
|
||||
- **Unauthorized Access:** Implement proper authentication and authorization mechanisms.
|
||||
- **Data Breaches:** Protect sensitive data by encrypting it at rest and in transit.
|
||||
|
||||
- ### Input Validation
|
||||
|
||||
- Validate user input to prevent injection attacks and data corruption.
|
||||
- Sanitize data before indexing it into Elasticsearch.
|
||||
- Use regular expressions or validation libraries to enforce data constraints.
|
||||
|
||||
- ### Authentication and Authorization
|
||||
|
||||
- Use Elasticsearch's built-in security features or a third-party plugin for authentication.
|
||||
- Implement role-based access control (RBAC) to restrict access to sensitive data.
|
||||
- Use API keys or tokens for secure API communication.
|
||||
|
||||
- ### Data Protection
|
||||
|
||||
- Encrypt sensitive data at rest using Elasticsearch's encryption features.
|
||||
- Encrypt data in transit using HTTPS.
|
||||
- Mask or redact sensitive data in logs and error messages.
|
||||
|
||||
- ### Secure API Communication
|
||||
|
||||
- Use HTTPS for all API communication with Elasticsearch.
|
||||
- Validate the server certificate to prevent man-in-the-middle attacks.
|
||||
- Use secure protocols like TLS 1.3 or higher.
|
||||
|
||||
- ## 5. Testing Approaches
|
||||
|
||||
- ### Unit Testing
|
||||
|
||||
- Unit test individual components in isolation.
|
||||
- Mock Elasticsearch dependencies to control test behavior.
|
||||
- Use assertion libraries to verify the expected results.
|
||||
|
||||
- ### Integration Testing
|
||||
|
||||
- Integrate test different components to verify their interaction.
|
||||
- Use a test Elasticsearch instance for integration tests.
|
||||
- Verify that data is correctly indexed and retrieved.
|
||||
|
||||
- ### End-to-End Testing
|
||||
|
||||
- Test the entire application from end to end.
|
||||
- Use automated testing frameworks like Selenium or Cypress.
|
||||
- Verify that the application functions correctly in a real-world environment.
|
||||
|
||||
- ### Test Organization
|
||||
|
||||
- Organize your tests into logical categories.
|
||||
- Use descriptive names for your test cases.
|
||||
- Keep your tests concise and focused.
|
||||
|
||||
- ### Mocking and Stubbing
|
||||
|
||||
- Use mocking libraries to create mock Elasticsearch clients and responses.
|
||||
- Use stubbing to simulate different Elasticsearch scenarios.
|
||||
- Verify that your code interacts with Elasticsearch as expected.
|
||||
|
||||
- ## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- ### Frequent Mistakes
|
||||
|
||||
- Not understanding Elasticsearch's query DSL.
|
||||
- Not configuring the Elasticsearch cluster properly.
|
||||
- Not monitoring Elasticsearch performance.
|
||||
|
||||
- ### Edge Cases
|
||||
|
||||
- Handling large result sets.
|
||||
- Dealing with complex data types.
|
||||
- Managing index mappings and updates.
|
||||
|
||||
- ### Version-Specific Issues
|
||||
|
||||
- Be aware of breaking changes between Elasticsearch versions.
|
||||
- Test your application thoroughly when upgrading Elasticsearch.
|
||||
- Consult the Elasticsearch documentation for version-specific information.
|
||||
|
||||
- ### Compatibility Concerns
|
||||
|
||||
- Ensure compatibility between Elasticsearch and your application's programming language.
|
||||
- Use compatible versions of Elasticsearch client libraries.
|
||||
|
||||
- ### Debugging Strategies
|
||||
|
||||
- Use Elasticsearch's logging features to troubleshoot issues.
|
||||
- Use the Elasticsearch API to inspect the cluster state.
|
||||
- Use debugging tools to step through your code.
|
||||
|
||||
- ## 7. Tooling and Environment
|
||||
|
||||
- ### Recommended Tools
|
||||
|
||||
- **Elasticsearch:** The core search and analytics engine.
|
||||
- **Kibana:** A visualization and exploration tool for Elasticsearch data.
|
||||
- **Logstash:** A data processing pipeline for ingesting data into Elasticsearch.
|
||||
- **Elasticsearch Head/Cerebro:** Cluster management and monitoring tools.
|
||||
|
||||
- ### Build Configuration
|
||||
|
||||
- Use a build tool like Maven, Gradle, or npm to manage dependencies.
|
||||
- Configure your build to package your application and its dependencies.
|
||||
|
||||
- ### Linting and Formatting
|
||||
|
||||
- Use a linter like ESLint or Pylint to enforce code style guidelines.
|
||||
- Use a formatter like Prettier or Black to automatically format your code.
|
||||
|
||||
- ### Deployment
|
||||
|
||||
- Deploy your Elasticsearch cluster to a cloud platform like AWS, Azure, or GCP.
|
||||
- Use containerization technologies like Docker and Kubernetes.
|
||||
- Automate your deployment process using tools like Ansible or Terraform.
|
||||
|
||||
- ### CI/CD
|
||||
|
||||
- Integrate your application with a CI/CD pipeline.
|
||||
- Automate testing, building, and deployment processes.
|
||||
- Use tools like Jenkins, GitLab CI, or CircleCI.
|
||||
|
||||
- ## Additional Best Practices
|
||||
|
||||
- **Monitoring:** Implement comprehensive monitoring of Elasticsearch cluster health, resource utilization, and query performance using tools like Prometheus, Grafana, and Elasticsearch's built-in monitoring features.
|
||||
- **Logging:** Configure detailed logging to capture important events, errors, and performance metrics for troubleshooting and analysis. Use structured logging formats like JSON for easier parsing and analysis.
|
||||
- **Backup and Recovery:** Implement regular backups of Elasticsearch data and configurations to prevent data loss. Test the recovery process to ensure it works as expected.
|
||||
- **Capacity Planning:** Regularly assess the capacity requirements of your Elasticsearch cluster based on data growth, query load, and indexing performance. Scale your cluster accordingly to maintain optimal performance.
|
||||
- **Security Auditing:** Conduct regular security audits to identify and address potential vulnerabilities. Review access controls, network configurations, and data encryption settings.
|
||||
- **Stay Updated:** Keep your Elasticsearch cluster and client libraries up to date with the latest security patches and bug fixes. Follow the Elasticsearch community for updates and best practices.
|
||||
|
||||
By following these best practices, you can build robust, scalable, and secure applications with Elasticsearch.
|
||||
# elasticsearch Best Practices
|
||||
|
||||
Elasticsearch is a powerful search engine. Treat it as such. These guidelines ensure your team builds performant, scalable, and maintainable applications.
|
||||
|
||||
## 1. Data Modeling
|
||||
|
||||
### 1.1. Define Explicit Mappings
|
||||
|
||||
Always define explicit mappings. This ensures data consistency, optimal indexing, and predictable search behavior. Avoid dynamic mapping for critical fields.
|
||||
|
||||
❌ **BAD: Relying on dynamic mapping**
|
||||
```json
|
||||
// Elasticsearch infers types, which can lead to 'text' for IDs or unexpected analyzers.
|
||||
PUT /my_index/_doc/1
|
||||
{
|
||||
"product_id": "P12345",
|
||||
"name": "Super Widget",
|
||||
"tags": ["electronics", "gadget"]
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD: Explicitly define field types**
|
||||
```json
|
||||
PUT /my_index
|
||||
{
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"product_id": { "type": "keyword" }, // Exact match, no analysis
|
||||
"name": { "type": "text", "analyzer": "standard" }, // Analyzed for full-text search
|
||||
"tags": { "type": "keyword" }, // Exact match for filtering/faceting
|
||||
"description": { "type": "text", "analyzer": "english" }, // Language-specific analysis
|
||||
"price": { "type": "float" },
|
||||
"created_at": { "type": "date" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2. Choose Correct Field Types
|
||||
|
||||
Use `keyword` for exact values (IDs, tags, enums) and `text` for analyzed, full-text content.
|
||||
|
||||
❌ **BAD: Using `text` for exact matching or IDs**
|
||||
```json
|
||||
// 'product_id' as text means it will be analyzed, making exact matches inefficient.
|
||||
GET /my_index/_search
|
||||
{
|
||||
"query": { "match": { "product_id": "P12345" } }
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD: Use `keyword` for exact values**
|
||||
```json
|
||||
GET /my_index/_search
|
||||
{
|
||||
"query": { "term": { "product_id": "P12345" } } // Efficient exact match
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3. Select Appropriate Analyzers
|
||||
|
||||
Use lightweight, specific analyzers. `standard` is a good default. For language-specific content, use analyzers like `english`. Define custom analyzers when needed.
|
||||
|
||||
❌ **BAD: Using `standard` for all text fields, including highly specific ones**
|
||||
```json
|
||||
// 'standard' might not be optimal for highly technical or language-specific content.
|
||||
{ "content": { "type": "text", "analyzer": "standard" } }
|
||||
```
|
||||
|
||||
✅ **GOOD: Use specific or custom analyzers**
|
||||
```json
|
||||
PUT /my_index
|
||||
{
|
||||
"settings": {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"code_analyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "whitespace",
|
||||
"filter": ["lowercase"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"title": { "type": "text", "analyzer": "standard" },
|
||||
"description": { "type": "text", "analyzer": "english" },
|
||||
"code_snippet": { "type": "text", "analyzer": "code_analyzer" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 1.4. Avoid Large Documents
|
||||
|
||||
Keep documents well under 100MB. Large documents stress network, memory, and disk. Reconsider your unit of information (e.g., chapters instead of whole books).
|
||||
|
||||
❌ **BAD: Indexing an entire book as one document**
|
||||
```json
|
||||
// Document size can easily exceed 100MB, leading to indexing failures and poor search.
|
||||
{ "book_title": "War and Peace", "full_text_content": "..." }
|
||||
```
|
||||
|
||||
✅ **GOOD: Break down large content into smaller, searchable units**
|
||||
```json
|
||||
// Index chapters or paragraphs, linking back to the parent book.
|
||||
{ "book_id": "B123", "chapter_title": "Chapter 1", "chapter_content": "..." }
|
||||
```
|
||||
|
||||
### 1.5. Shard Sizing
|
||||
|
||||
Aim for shard sizes between 10GB and 50GB, and under 200 million documents per shard. Oversharding or huge shards degrade performance.
|
||||
|
||||
❌ **BAD: Default shard count for small indices, leading to many tiny shards**
|
||||
```json
|
||||
// An index with 1GB data and 5 primary shards is oversharded.
|
||||
PUT /my_small_index { "settings": { "number_of_shards": 5 } }
|
||||
```
|
||||
|
||||
✅ **GOOD: Calculate shards based on expected data volume and shard size goals**
|
||||
```json
|
||||
// For 50GB of data, 1-5 primary shards is appropriate.
|
||||
PUT /my_index { "settings": { "number_of_shards": 1 } }
|
||||
```
|
||||
|
||||
### 1.6. Use Data Streams and ILM for Time-Series
|
||||
|
||||
For time-series data (logs, metrics), always use data streams with Index Lifecycle Management (ILM) for automatic rollover and shard management.
|
||||
|
||||
✅ **GOOD: Manage time-series data with data streams and ILM**
|
||||
```json
|
||||
// Define an ILM policy and a component template for your data stream.
|
||||
// Data streams automatically roll over backing indices based on size/age,
|
||||
// preventing large, unmanageable shards.
|
||||
PUT /_index_template/my_logs_template
|
||||
{
|
||||
"index_patterns": ["my-logs-*"],
|
||||
"data_stream": {},
|
||||
"template": {
|
||||
"settings": { "index.lifecycle.name": "my_log_policy" },
|
||||
"mappings": { "properties": { "timestamp": { "type": "date" } } }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Query Optimization
|
||||
|
||||
### 2.1. Avoid Returning Large Result Sets
|
||||
|
||||
Elasticsearch is a search engine, not a database for full table scans. For deep pagination, use the `Scroll` API. For user-facing pagination, keep `size` small (e.g., 10-100).
|
||||
|
||||
❌ **BAD: Attempting to retrieve all documents with `size: 10000` or more**
|
||||
```json
|
||||
GET /my_index/_search
|
||||
{ "query": { "match_all": {} }, "size": 10000 } // High memory/network pressure
|
||||
```
|
||||
|
||||
✅ **GOOD: Use `Scroll` API for deep pagination or bulk processing**
|
||||
```json
|
||||
// Initial scroll request
|
||||
GET /my_index/_search?scroll=1m
|
||||
{ "query": { "match_all": {} }, "size": 1000 }
|
||||
|
||||
// Subsequent scroll requests
|
||||
GET /_search/scroll
|
||||
{ "scroll": "1m", "scroll_id": "FGluY2x1ZGVfY29udGV4dF91dWlk..." }
|
||||
```
|
||||
|
||||
### 2.2. Prefer `filter` for Non-Scoring Queries
|
||||
|
||||
Use `filter` clauses within a `bool` query for conditions that should not affect the relevance score (e.g., exact matches, ranges). This is more performant as filters are cached.
|
||||
|
||||
❌ **BAD: Using `must` for non-scoring criteria**
|
||||
```json
|
||||
GET /my_index/_search
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{ "match": { "description": "search term" } },
|
||||
{ "term": { "category": "electronics" } } // This should be a filter
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD: Use `filter` for non-scoring criteria**
|
||||
```json
|
||||
GET /my_index/_search
|
||||
{
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": { "match": { "description": "search term" } },
|
||||
"filter": { "term": { "category": "electronics" } } // Cached, no score impact
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.3. Boost Fields Judiciously
|
||||
|
||||
Use boosting to influence relevance scores, but test extensively. Over-boosting can lead to irrelevant results.
|
||||
|
||||
✅ **GOOD: Boost important fields for relevance**
|
||||
```json
|
||||
GET /my_index/_search
|
||||
{
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": "Elasticsearch performance",
|
||||
"fields": ["title^3", "description^1.5", "tags"] // Title is most important
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Code Organization and Structure
|
||||
|
||||
### 3.1. Centralize Client Configuration
|
||||
|
||||
Keep Elasticsearch client settings (hosts, timeouts, retries) in a shared module or configuration file.
|
||||
|
||||
❌ **BAD: Hardcoding client settings in multiple places**
|
||||
```python
|
||||
# client.py
|
||||
es_client = Elasticsearch(
|
||||
hosts=['localhost:9200'],
|
||||
timeout=30,
|
||||
max_retries=10
|
||||
)
|
||||
# another_module.py
|
||||
another_es_client = Elasticsearch(
|
||||
hosts=['localhost:9200'],
|
||||
timeout=30,
|
||||
max_retries=10
|
||||
)
|
||||
```
|
||||
|
||||
✅ **GOOD: Centralize client configuration**
|
||||
```python
|
||||
# config.py
|
||||
ELASTICSEARCH_HOSTS = ['https://es-cluster.mycompany.com:9200']
|
||||
ELASTICSEARCH_TIMEOUT = 60
|
||||
ELASTICSEARCH_MAX_RETRIES = 5
|
||||
ELASTICSEARCH_API_KEY = "..." # Use API keys or username/password
|
||||
|
||||
# es_client.py
|
||||
from elasticsearch import Elasticsearch
|
||||
from .config import ELASTICSEARCH_HOSTS, ELASTICSEARCH_TIMEOUT, ELASTICSEARCH_MAX_RETRIES, ELASTICSEARCH_API_KEY
|
||||
|
||||
es = Elasticsearch(
|
||||
hosts=ELASTICSEARCH_HOSTS,
|
||||
timeout=ELASTICSEARCH_TIMEOUT,
|
||||
max_retries=ELASTICSEARCH_MAX_RETRIES,
|
||||
api_key=ELASTICSEARCH_API_KEY
|
||||
)
|
||||
|
||||
# In your application code
|
||||
from .es_client import es
|
||||
results = es.search(index="my_index", query={"match_all": {}})
|
||||
```
|
||||
|
||||
### 3.2. Centralize Mapping Definitions
|
||||
|
||||
Store index mapping definitions in version-controlled JSON/YAML files. Apply them programmatically.
|
||||
|
||||
❌ **BAD: Defining mappings ad-hoc or inline in application code**
|
||||
```python
|
||||
# In some script
|
||||
es.indices.create(index="products", body={"mappings": {"properties": {"name": {"type": "text"}}}})
|
||||
```
|
||||
|
||||
✅ **GOOD: Store mappings in dedicated files**
|
||||
```json
|
||||
// mappings/products.json
|
||||
{
|
||||
"properties": {
|
||||
"product_id": { "type": "keyword" },
|
||||
"name": { "type": "text", "analyzer": "standard" },
|
||||
"description": { "type": "text", "analyzer": "english" },
|
||||
"price": { "type": "float" },
|
||||
"available": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
```
|
||||
```python
|
||||
# scripts/init_indices.py
|
||||
import json
|
||||
from es_client import es
|
||||
|
||||
def create_index(index_name, mapping_file):
|
||||
with open(f"mappings/{mapping_file}.json", "r") as f:
|
||||
mapping = json.load(f)
|
||||
if not es.indices.exists(index=index_name):
|
||||
es.indices.create(index=index_name, mappings=mapping)
|
||||
print(f"Index '{index_name}' created.")
|
||||
else:
|
||||
print(f"Index '{index_name}' already exists.")
|
||||
|
||||
create_index("products", "products")
|
||||
```
|
||||
|
||||
## 4. Performance Considerations
|
||||
|
||||
### 4.1. Bulk Indexing
|
||||
|
||||
Always use the bulk API for indexing multiple documents. This significantly reduces network overhead and improves indexing throughput.
|
||||
|
||||
❌ **BAD: Indexing documents one by one in a loop**
|
||||
```python
|
||||
for doc in documents:
|
||||
es.index(index="my_index", id=doc["id"], document=doc)
|
||||
```
|
||||
|
||||
✅ **GOOD: Use the bulk API**
|
||||
```python
|
||||
from elasticsearch.helpers import bulk
|
||||
|
||||
actions = [
|
||||
{"_index": "my_index", "_id": doc["id"], "_source": doc}
|
||||
for doc in documents
|
||||
]
|
||||
bulk(es, actions)
|
||||
```
|
||||
|
||||
### 4.2. Monitor and Benchmark
|
||||
|
||||
Continuously monitor your cluster's health, performance, and resource usage. Benchmark with realistic data and query loads before deploying changes.
|
||||
|
||||
✅ **GOOD: Use Kibana's monitoring tools and run load tests**
|
||||
```bash
|
||||
# Example: Use a tool like k6 or JMeter to simulate production load
|
||||
k6 run load_test_script.js --vus 100 --duration 30s
|
||||
```
|
||||
|
||||
## 5. Common Pitfalls
|
||||
|
||||
### 5.1. `fielddata` on `text` fields
|
||||
|
||||
Enabling `fielddata` on `text` fields for sorting or aggregations consumes large amounts of heap memory and can lead to `OutOfMemoryError`. Use `keyword` fields for these operations.
|
||||
|
||||
❌ **BAD: Enabling `fielddata` on a `text` field**
|
||||
```json
|
||||
PUT /my_index/_mapping
|
||||
{
|
||||
"properties": {
|
||||
"description": { "type": "text", "fielddata": true } // Avoid this!
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
✅ **GOOD: Use `keyword` fields for sorting/aggregations**
|
||||
```json
|
||||
PUT /my_index/_mapping
|
||||
{
|
||||
"properties": {
|
||||
"description": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": { "type": "keyword", "ignore_above": 256 } // Use this for sorting/aggregations
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2. Oversharding
|
||||
|
||||
Too many small shards degrade search performance and cluster stability. Each shard has overhead.
|
||||
|
||||
❌ **BAD: Creating an index with 100 shards for 10GB of data**
|
||||
```json
|
||||
PUT /my_index { "settings": { "number_of_shards": 100 } }
|
||||
```
|
||||
|
||||
✅ **GOOD: Target 10-50GB per shard**
|
||||
```json
|
||||
// For 10GB data, 1 shard is sufficient.
|
||||
PUT /my_index { "settings": { "number_of_shards": 1 } }
|
||||
```
|
||||
|
||||
## 6. Security Best Practices
|
||||
|
||||
### 6.1. Enable Security Features
|
||||
|
||||
Always enable Elasticsearch security (authentication, authorization, TLS/SSL) in production. Use API keys or role-based access control.
|
||||
|
||||
❌ **BAD: Running Elasticsearch without security in production**
|
||||
```bash
|
||||
# No authentication, anyone can access
|
||||
```
|
||||
|
||||
✅ **GOOD: Configure API keys and TLS**
|
||||
```python
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
es = Elasticsearch(
|
||||
hosts=['https://es-cluster.mycompany.com:9200'],
|
||||
api_key=("id", "api_key_value"), # Use API keys
|
||||
verify_certs=True,
|
||||
ca_certs="/path/to/ca.crt"
|
||||
)
|
||||
```
|
||||
|
||||
### 6.2. Network Isolation
|
||||
|
||||
Restrict network access to Elasticsearch nodes. Only allow necessary traffic from application servers.
|
||||
|
||||
✅ **GOOD: Use firewalls/security groups to limit access**
|
||||
```bash
|
||||
# Example: AWS Security Group rule
|
||||
# Inbound: TCP 9200 from application server IPs only
|
||||
```
|
||||
Reference in New Issue
Block a user