# Install Elasticsearch client pip install elasticsearch # For async support pip install elasticsearch[async] # For development with additional features pip install elasticsearch[dev]
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
# Basic connection
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
# With authentication
es = Elasticsearch(
['localhost:9200'],
http_auth=('username', 'password'),
verify_certs=True,
ca_certs='/path/to/ca_certs.pem'
)
# Cloud connection
es = Elasticsearch(
cloud_id="your_cloud_id",
http_auth=('elastic', 'password')
)
# Check connection
if es.ping():
print("Connected to Elasticsearch!")
else:
print("Could not connect to Elasticsearch")# Create a single document
doc = {
'title': 'Elasticsearch Guide',
'content': 'Comprehensive guide',
'tags': ['elasticsearch', 'search'],
'created_at': '2024-01-15T10:30:00Z'
}
# Index with auto-generated ID
result = es.index(index='articles', body=doc)
print(f"Created ID: {result['_id']}")
# Index with specific ID
result = es.index(index='articles', id=1, body=doc)
# Bulk indexing
documents = [
{'_index': 'articles', '_source': {'title': 'Doc 1'}},
{'_index': 'articles', '_source': {'title': 'Doc 2'}},
]
bulk(es, documents)# Get document by ID
doc = es.get(index='articles', id=1)
print(doc['_source'])
# Search documents
search_body = {
'query': {
'match': { 'title': 'Elasticsearch' }
}
}
result = es.search(index='articles', body=search_body)
for hit in result['hits']['hits']:
print(f"Score: {hit['_score']}")
# Search with bool filter
search_body = {
'query': {
'bool': {
'must': [
{'match': {'title': 'guide'}},
{'term': {'tags': 'elasticsearch'}}
],
'filter': [
{'range': {'created_at': {'gte': '2024-01-01'}}}
]
}
}
}
result = es.search(index='articles', body=search_body)# Partial update using script
update_body = {
'script': {
'source': 'ctx._source.views += params.views',
'params': {'views': 1}
}
}
result = es.update(index='articles', id=1, body=update_body)
# Partial update with doc
update_body = {
'doc': {
'title': 'New Title',
'updated_at': '2024-01-16T10:30:00Z'
}
}
result = es.update(index='articles', id=1, body=update_body)
# Replace entire document
updated_doc = {
'title': 'Updated Elasticsearch Guide',
'tags': ['elasticsearch', 'updated'],
}
result = es.index(index='articles', id=1, body=updated_doc)# Delete document by ID
result = es.delete(index='articles', id=1)
print(f"Deleted: {result['result']}")
# Delete by query
delete_query = {
'query': {
'term': {'status': 'inactive'}
}
}
result = es.delete_by_query(index='articles', body=delete_query)
print(f"Deleted {result['deleted']} documents")
# Delete entire index
result = es.indices.delete(index='articles')# Terms aggregation
search_body = {
'size': 0,
'aggs': {
'popular_tags': {
'terms': {
'field': 'tags.keyword',
'size': 10
}
}
}
}
result = es.search(index='articles', body=search_body)
for bucket in result['aggregations']['popular_tags']['buckets']:
print(f"Tag: {bucket['key']}, Count: {bucket['doc_count']}")
# Date histogram aggregation
search_body = {
'size': 0,
'aggs': {
'articles_over_time': {
'date_histogram': {
'field': 'created_at',
'calendar_interval': 'month'
}
}
}
}
result = es.search(index='articles', body=search_body)# Multi-match query
search_body = {
'query': {
'multi_match': {
'query': 'elasticsearch guide',
'fields': ['title^2', 'content'],
'type': 'best_fields',
'fuzziness': 'AUTO'
}
}
}
result = es.search(index='articles', body=search_body)
# Bool query with should
search_body = {
'query': {
'bool': {
'should': [
{'match': {'title': 'elasticsearch'}},
{'match': {'content': 'elasticsearch'}},
{'match': {'tags': 'elasticsearch'}}
],
'minimum_should_match': 1
}
}
}
result = es.search(index='articles', body=search_body)# Install Laravel Scout composer require laravel/scout # Install Elasticsearch driver composer require tamayo/laravel-scout-elastic # Publish Scout configuration php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" # Publish Elasticsearch configuration php artisan vendor:publish --provider="Tamayo\LaravelScoutElastic\ScoutElasticServiceProvider"
# .env configuration
SCOUT_DRIVER=elastic
ELASTICSEARCH_HOST=localhost:9200
ELASTICSEARCH_INDEX=laravel
# config/scout.php
'elastic' => [
'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
'hosts' => [
env('ELASTICSEARCH_HOST', 'localhost:9200'),
],
],
# config/database.php (add to connections)
'elasticsearch' => [
'driver' => 'elasticsearch',
'host' => env('ELASTICSEARCH_HOST', 'localhost:9200'),
'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
],<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Article extends Model
{
use Searchable;
protected $fillable = ['title', 'content', 'tags', 'published_at', 'views'];
protected $casts = [
'tags' => 'array',
'published_at' => 'datetime',
];
public function toSearchableArray()
{
return [
'title' => $this->title,
'content' => $this->content,
'tags' => $this->tags,
'published_at' => $this->published_at?->toISOString(),
'views' => $this->views,
];
}
public function searchableAs()
{
return 'articles_index';
}
public function shouldBeSearchable()
{
return $this->published_at !== null;
}
}<?php
// Create and automatically index
$article = Article::create([
'title' => 'Laravel Elasticsearch Guide',
'content' => 'Comprehensive guide',
'tags' => ['laravel', 'elasticsearch'],
'published_at' => now(),
'views' => 0
]);
// Manually index existing model
$article->searchable();
// Bulk index all models
Article::makeAllSearchable();
// Index specific models
Article::where('published_at', '!=', null)->searchable();
// Remove from search index
$article->unsearchable();<?php
// Basic search
$articles = Article::search('elasticsearch')->get();
// Search with pagination
$articles = Article::search('laravel guide')
->paginate(15);
// Advanced search with filters
$articles = Article::search('elasticsearch')
->where('tags', 'laravel')
->where('views', '>', 100)
->orderBy('published_at', 'desc')
->get();
// Search with custom query
$articles = Article::search('', function ($es, $query) {
return $es->search($query, [
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['title' => 'elasticsearch']],
],
'filter' => [
['term' => ['tags' => 'laravel']]
]
]
]
]
]);
})->get();# Import all models to search index
php artisan scout:import "App\Models\Article"
# Flush all models from search index
php artisan scout:flush "App\Models\Article"
# Create custom search command
php artisan make:command SearchArticles
# Example custom command
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Article;
class SearchArticles extends Command
{
protected $signature = 'search:articles {query}';
protected $description = 'Search articles in Elasticsearch';
public function handle()
{
$query = $this->argument('query');
$articles = Article::search($query)->get();
$this->info("Found {$articles->count()} articles:");
foreach ($articles as $article) {
$this->line("- {$article->title}");
}
}
}{
"query": {
"match": {
"title": "elasticsearch guide"
}
}
}{
"query": {
"bool": {
"must": [
{ "match": { "title": "elasticsearch" } }
],
"should": [
{ "match": { "content": "guide" } },
{ "match": { "tags": "tutorial" } }
],
"filter": [
{ "term": { "status": "published" } },
{ "range": { "created_at": { "gte": "2024-01-01" } } }
],
"must_not": [
{ "term": { "category": "draft" } }
]
}
}
}{
"size": 0,
"aggs": {
"popular_tags": {
"terms": {
"field": "tags.keyword",
"size": 10
}
},
"avg_views": {
"avg": { "field": "views" }
},
"articles_by_month": {
"date_histogram": {
"field": "created_at",
"calendar_interval": "month"
}
}
}
}{
"size": 0,
"aggs": {
"view_ranges": {
"range": {
"field": "views",
"ranges": [
{ "to": 100 },
{ "from": 100, "to": 1000 },
{ "from": 1000 }
]
}
}
}
}