or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregations.mdanalysis.mdconnections.mddocument-operations.mdfield-types.mdindex-management.mdindex.mdsearch-queries.md

index.mddocs/

0

# Elasticsearch DSL

1

2

A high-level Python library for Elasticsearch that provides an idiomatic way to write and manipulate queries. Built on top of the official low-level elasticsearch-py client, it stays close to the Elasticsearch JSON DSL while exposing the whole range of functionality through Python classes and expressions. This package also provides optional document persistence with Python object mapping and index management capabilities.

3

4

**Note**: As of version 8.18.0, this package serves as a compatibility layer that redirects imports to elasticsearch.dsl in the main elasticsearch package.

5

6

## Package Information

7

8

- **Package Name**: elasticsearch-dsl

9

- **Language**: Python

10

- **Installation**: `pip install elasticsearch-dsl`

11

- **Python Support**: 3.8+

12

- **Dependencies**: elasticsearch>=8.0.0, python-dateutil, typing-extensions

13

14

## Core Imports

15

16

```python

17

import elasticsearch_dsl

18

```

19

20

Common imports for document and search operations:

21

22

```python

23

from elasticsearch_dsl import Document, Search, Q, A, connections

24

```

25

26

Field types for document mapping:

27

28

```python

29

from elasticsearch_dsl import Text, Keyword, Date, Integer, Boolean, Object, Nested

30

```

31

32

## Basic Usage

33

34

```python

35

from elasticsearch_dsl import Document, Search, Text, Keyword, Date, Integer, connections

36

37

# Configure connection

38

connections.create_connection(hosts=['localhost:9200'])

39

40

# Define a document

41

class Article(Document):

42

title = Text(analyzer='snowball')

43

body = Text(analyzer='snowball')

44

tags = Keyword()

45

published_date = Date()

46

view_count = Integer()

47

48

class Index:

49

name = 'blog_articles'

50

51

# Create index and mappings

52

Article.init()

53

54

# Create and save a document

55

article = Article(

56

title='Getting Started with Elasticsearch DSL',

57

body='This article explains how to use elasticsearch-dsl...',

58

tags=['elasticsearch', 'python', 'tutorial'],

59

published_date='2023-10-01',

60

view_count=150

61

)

62

article.save()

63

64

# Search for documents

65

search = Search(index='blog_articles')

66

search = search.filter('term', tags='elasticsearch')

67

search = search.query('match', title='elasticsearch')

68

69

response = search.execute()

70

for hit in response:

71

print(f"{hit.title} - Views: {hit.view_count}")

72

```

73

74

## Architecture

75

76

Elasticsearch DSL organizes functionality into several key components:

77

78

- **Documents**: Object-relational mapping between Python objects and Elasticsearch documents

79

- **Search**: Query builder and execution with fluent API

80

- **Fields**: Type system for document structure and Elasticsearch mapping

81

- **Queries**: Comprehensive query DSL mirroring Elasticsearch's JSON query syntax

82

- **Aggregations**: Statistical analysis and data grouping operations

83

- **Analysis**: Text processing, tokenization, and custom analyzer configuration

84

- **Connections**: Client connection management with support for multiple clusters

85

86

This architecture enables both simple document operations and complex analytical queries while maintaining type safety and providing a Pythonic interface to Elasticsearch's full feature set.

87

88

## Capabilities

89

90

### Document Operations

91

92

Object-relational mapping for Elasticsearch documents with automatic index management, CRUD operations, bulk processing, and lifecycle hooks. Supports both synchronous and asynchronous operations.

93

94

```python { .api }

95

class Document:

96

def __init__(self, **kwargs): ...

97

def save(self, **kwargs): ...

98

def delete(self, **kwargs): ...

99

@classmethod

100

def get(cls, id, **kwargs): ...

101

@classmethod

102

def init(cls, **kwargs): ...

103

104

class AsyncDocument:

105

async def save(self, **kwargs): ...

106

async def delete(self, **kwargs): ...

107

@classmethod

108

async def get(cls, id, **kwargs): ...

109

```

110

111

[Document Operations](./document-operations.md)

112

113

### Search and Query Building

114

115

Fluent API for building and executing Elasticsearch queries with support for filtering, sorting, pagination, and result processing. Includes both basic and advanced query types.

116

117

```python { .api }

118

class Search:

119

def __init__(self, **kwargs): ...

120

def query(self, query, **kwargs): ...

121

def filter(self, query, **kwargs): ...

122

def exclude(self, query, **kwargs): ...

123

def sort(self, *keys): ...

124

def execute(self): ...

125

126

def Q(name, **params): ...

127

```

128

129

[Search and Queries](./search-queries.md)

130

131

### Field Types and Mapping

132

133

Comprehensive field type system for defining document structure and Elasticsearch mappings with support for all Elasticsearch field types including text, numeric, date, geographic, and specialized fields.

134

135

```python { .api }

136

class Text:

137

def __init__(self, analyzer=None, **kwargs): ...

138

139

class Keyword:

140

def __init__(self, **kwargs): ...

141

142

class Date:

143

def __init__(self, format=None, **kwargs): ...

144

145

class Integer:

146

def __init__(self, **kwargs): ...

147

148

class Object:

149

def __init__(self, properties=None, **kwargs): ...

150

151

class Nested:

152

def __init__(self, **kwargs): ...

153

```

154

155

[Field Types](./field-types.md)

156

157

### Aggregations and Analytics

158

159

Statistical analysis and data grouping with support for metric aggregations, bucket aggregations, and pipeline aggregations. Enables complex analytical queries and data summarization.

160

161

```python { .api }

162

def A(name, **params): ...

163

164

class Aggs:

165

def bucket(self, name, agg_type, **params): ...

166

def metric(self, name, agg_type, **params): ...

167

```

168

169

[Aggregations](./aggregations.md)

170

171

### Text Analysis and Processing

172

173

Custom analyzer creation, tokenizer configuration, and text processing setup for multilingual and domain-specific search requirements.

174

175

```python { .api }

176

def analyzer(name, **kwargs): ...

177

def tokenizer(name, **kwargs): ...

178

def char_filter(name, **kwargs): ...

179

def token_filter(name, **kwargs): ...

180

```

181

182

[Analysis](./analysis.md)

183

184

### Connection Management

185

186

Connection configuration and management for single and multiple Elasticsearch clusters with support for authentication, SSL, connection pooling, and both synchronous and asynchronous clients.

187

188

```python { .api }

189

def create_connection(alias='default', **kwargs): ...

190

def get_connection(alias='default'): ...

191

def configure(**kwargs): ...

192

193

# Async variants

194

def create_async_connection(alias='default', **kwargs): ...

195

def get_async_connection(alias='default'): ...

196

```

197

198

[Connections](./connections.md)

199

200

### Index Management and Operations

201

202

Index creation, configuration, and lifecycle management with support for settings, mappings, aliases, and templates. Enables comprehensive control over Elasticsearch indices and their behavior.

203

204

```python { .api }

205

class Index:

206

def __init__(self, name, using=None): ...

207

def settings(self, **kwargs): ...

208

def create(self, ignore=400, **kwargs): ...

209

def delete(self, ignore=404, **kwargs): ...

210

211

class IndexTemplate:

212

def __init__(self, name, using=None): ...

213

def body(self, **kwargs): ...

214

def create(self, **kwargs): ...

215

```

216

217

[Index Management](./index-management.md)

218

219

## Error Handling

220

221

The library raises specific exceptions for different error conditions:

222

223

```python { .api }

224

class ElasticsearchDslException(Exception): ...

225

class UnknownDslObject(ElasticsearchDslException): ...

226

class ValidationException(ElasticsearchDslException): ...

227

class IllegalOperation(ElasticsearchDslException): ...

228

```

229

230

Common exceptions from the underlying elasticsearch package should also be handled in application code.