or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-operations.mdcluster-management.mdesql-operations.mdexception-handling.mdhelper-functions.mdindex-management.mdindex.mdinference-api.mdlifecycle-management.mdmachine-learning.mdquery-dsl.mdsearch-operations.mdsecurity-operations.mdvectorstore-helpers.md

search-operations.mddocs/

0

# Search Operations

1

2

Advanced search capabilities including complex queries, aggregations, scrolling, and search templates. These operations provide comprehensive search functionality for retrieving and analyzing data from Elasticsearch.

3

4

## Capabilities

5

6

### Multi-Search

7

8

Execute multiple search queries in a single request for improved performance.

9

10

```python { .api }

11

def msearch(

12

self,

13

searches: List[Dict[str, Any]],

14

index: Optional[str] = None,

15

routing: Optional[str] = None,

16

max_concurrent_searches: Optional[int] = None,

17

rest_total_hits_as_int: Optional[bool] = None,

18

typed_keys: Optional[bool] = None,

19

**kwargs

20

) -> ObjectApiResponse:

21

"""

22

Execute multiple search queries.

23

24

Parameters:

25

- searches: List of search query dictionaries

26

- index: Default index for searches without explicit index

27

- routing: Default routing value

28

- max_concurrent_searches: Maximum number of concurrent searches

29

- rest_total_hits_as_int: Whether to return total hits as integer

30

- typed_keys: Whether to prefix aggregation names with type

31

32

Returns:

33

ObjectApiResponse with array of search results

34

"""

35

```

36

37

### Scroll Search

38

39

Efficiently retrieve large result sets using scroll context.

40

41

```python { .api }

42

def scroll(

43

self,

44

scroll_id: str,

45

scroll: str = "5m",

46

rest_total_hits_as_int: Optional[bool] = None,

47

**kwargs

48

) -> ObjectApiResponse:

49

"""

50

Retrieve next batch of results from scroll context.

51

52

Parameters:

53

- scroll_id: Scroll context ID from previous search

54

- scroll: Time to keep scroll context alive

55

- rest_total_hits_as_int: Whether total hits should be integer

56

57

Returns:

58

ObjectApiResponse with next batch of results

59

"""

60

61

def clear_scroll(

62

self,

63

scroll_id: Optional[Union[str, List[str]]] = None,

64

**kwargs

65

) -> ObjectApiResponse:

66

"""

67

Clear scroll contexts to free resources.

68

69

Parameters:

70

- scroll_id: Scroll ID(s) to clear, or None to clear all

71

72

Returns:

73

ObjectApiResponse with clearing results

74

"""

75

```

76

77

### Point in Time

78

79

Create stable snapshots for consistent pagination across result sets.

80

81

```python { .api }

82

def open_point_in_time(

83

self,

84

index: Union[str, List[str]],

85

keep_alive: str,

86

routing: Optional[str] = None,

87

preference: Optional[str] = None,

88

ignore_unavailable: Optional[bool] = None,

89

**kwargs

90

) -> ObjectApiResponse:

91

"""

92

Open a point in time for consistent search pagination.

93

94

Parameters:

95

- index: Index name(s) to create point in time for

96

- keep_alive: Time to keep point in time alive

97

- routing: Custom routing value

98

- preference: Node preference

99

- ignore_unavailable: Whether to ignore unavailable indices

100

101

Returns:

102

ObjectApiResponse with point in time ID

103

"""

104

105

def close_point_in_time(

106

self,

107

id: str,

108

**kwargs

109

) -> ObjectApiResponse:

110

"""

111

Close a point in time to free resources.

112

113

Parameters:

114

- id: Point in time ID to close

115

116

Returns:

117

ObjectApiResponse with closing result

118

"""

119

```

120

121

### Search Templates

122

123

Use pre-defined search templates with parameterization.

124

125

```python { .api }

126

def search_template(

127

self,

128

index: Optional[Union[str, List[str]]] = None,

129

id: Optional[str] = None,

130

params: Optional[Dict[str, Any]] = None,

131

source: Optional[str] = None,

132

explain: Optional[bool] = None,

133

profile: Optional[bool] = None,

134

routing: Optional[str] = None,

135

scroll: Optional[str] = None,

136

preference: Optional[str] = None,

137

**kwargs

138

) -> ObjectApiResponse:

139

"""

140

Execute a search using a template.

141

142

Parameters:

143

- index: Index name(s) to search

144

- id: Stored template ID

145

- params: Template parameters

146

- source: Inline template source

147

- explain: Whether to include explanation

148

- profile: Whether to include profiling

149

- routing: Custom routing value

150

- scroll: Scroll time for large result sets

151

- preference: Node preference

152

153

Returns:

154

ObjectApiResponse with search results

155

"""

156

157

def msearch_template(

158

self,

159

search_templates: List[Dict[str, Any]],

160

index: Optional[str] = None,

161

routing: Optional[str] = None,

162

max_concurrent_searches: Optional[int] = None,

163

rest_total_hits_as_int: Optional[bool] = None,

164

typed_keys: Optional[bool] = None,

165

**kwargs

166

) -> ObjectApiResponse:

167

"""

168

Execute multiple templated searches.

169

170

Parameters:

171

- search_templates: List of template search specifications

172

- index: Default index name

173

- routing: Default routing value

174

- max_concurrent_searches: Maximum concurrent searches

175

- rest_total_hits_as_int: Whether total hits should be integer

176

- typed_keys: Whether to prefix aggregation names

177

178

Returns:

179

ObjectApiResponse with array of template search results

180

"""

181

182

def render_search_template(

183

self,

184

id: Optional[str] = None,

185

params: Optional[Dict[str, Any]] = None,

186

source: Optional[str] = None,

187

**kwargs

188

) -> ObjectApiResponse:

189

"""

190

Render a search template without executing.

191

192

Parameters:

193

- id: Stored template ID

194

- params: Template parameters

195

- source: Inline template source

196

197

Returns:

198

ObjectApiResponse with rendered template

199

"""

200

```

201

202

### Count Operations

203

204

Count documents matching queries without retrieving them.

205

206

```python { .api }

207

def count(

208

self,

209

index: Optional[Union[str, List[str]]] = None,

210

query: Optional[Dict[str, Any]] = None,

211

routing: Optional[str] = None,

212

preference: Optional[str] = None,

213

analyzer: Optional[str] = None,

214

analyze_wildcard: Optional[bool] = None,

215

default_operator: Optional[str] = None,

216

df: Optional[str] = None,

217

lenient: Optional[bool] = None,

218

terminate_after: Optional[int] = None,

219

**kwargs

220

) -> ObjectApiResponse:

221

"""

222

Count documents matching a query.

223

224

Parameters:

225

- index: Index name(s) to count in

226

- query: Query to match documents

227

- routing: Custom routing value

228

- preference: Node preference

229

- analyzer: Analyzer for query string

230

- analyze_wildcard: Whether to analyze wildcards

231

- default_operator: Default boolean operator (AND/OR)

232

- df: Default field for query string

233

- lenient: Whether to ignore format errors

234

- terminate_after: Stop counting after this many docs

235

236

Returns:

237

ObjectApiResponse with count result

238

"""

239

```

240

241

### Field Capabilities

242

243

Discover field mappings and capabilities across indices.

244

245

```python { .api }

246

def field_caps(

247

self,

248

fields: Union[str, List[str]],

249

index: Optional[Union[str, List[str]]] = None,

250

ignore_unavailable: Optional[bool] = None,

251

allow_no_indices: Optional[bool] = None,

252

expand_wildcards: Optional[str] = None,

253

include_unmapped: Optional[bool] = None,

254

**kwargs

255

) -> ObjectApiResponse:

256

"""

257

Get field mapping capabilities across indices.

258

259

Parameters:

260

- fields: Field name(s) to analyze

261

- index: Index name(s) to analyze

262

- ignore_unavailable: Whether to ignore unavailable indices

263

- allow_no_indices: Whether empty index list is acceptable

264

- expand_wildcards: How to expand wildcard patterns

265

- include_unmapped: Whether to include unmapped fields

266

267

Returns:

268

ObjectApiResponse with field capabilities

269

"""

270

```

271

272

### Explain Queries

273

274

Get detailed explanation of query scoring and matching.

275

276

```python { .api }

277

def explain(

278

self,

279

index: str,

280

id: str,

281

query: Optional[Dict[str, Any]] = None,

282

routing: Optional[str] = None,

283

preference: Optional[str] = None,

284

analyzer: Optional[str] = None,

285

analyze_wildcard: Optional[bool] = None,

286

default_operator: Optional[str] = None,

287

df: Optional[str] = None,

288

lenient: Optional[bool] = None,

289

_source: Optional[Union[bool, List[str]]] = None,

290

_source_excludes: Optional[List[str]] = None,

291

_source_includes: Optional[List[str]] = None,

292

stored_fields: Optional[List[str]] = None,

293

**kwargs

294

) -> ObjectApiResponse:

295

"""

296

Explain why a document matches or doesn't match a query.

297

298

Parameters:

299

- index: Index name

300

- id: Document ID to explain

301

- query: Query to explain against

302

- routing: Custom routing value

303

- preference: Node preference

304

- analyzer: Analyzer for query string

305

- analyze_wildcard: Whether to analyze wildcards

306

- default_operator: Default boolean operator

307

- df: Default field for query string

308

- lenient: Whether to ignore format errors

309

- _source: Source field configuration

310

- _source_excludes: Source fields to exclude

311

- _source_includes: Source fields to include

312

- stored_fields: Stored fields to retrieve

313

314

Returns:

315

ObjectApiResponse with explanation details

316

"""

317

```

318

319

### Search Shards

320

321

Get information about which shards a search will execute on.

322

323

```python { .api }

324

def search_shards(

325

self,

326

index: Optional[Union[str, List[str]]] = None,

327

routing: Optional[str] = None,

328

preference: Optional[str] = None,

329

local: Optional[bool] = None,

330

ignore_unavailable: Optional[bool] = None,

331

allow_no_indices: Optional[bool] = None,

332

expand_wildcards: Optional[str] = None,

333

**kwargs

334

) -> ObjectApiResponse:

335

"""

336

Get search shard information.

337

338

Parameters:

339

- index: Index name(s) to get shard info for

340

- routing: Custom routing value

341

- preference: Node preference

342

- local: Whether to return local information only

343

- ignore_unavailable: Whether to ignore unavailable indices

344

- allow_no_indices: Whether empty index list is acceptable

345

- expand_wildcards: How to expand wildcard patterns

346

347

Returns:

348

ObjectApiResponse with shard routing information

349

"""

350

```

351

352

### Rank Evaluation

353

354

Evaluate search quality using relevance metrics.

355

356

```python { .api }

357

def rank_eval(

358

self,

359

requests: List[Dict[str, Any]],

360

metric: Dict[str, Any],

361

index: Optional[Union[str, List[str]]] = None,

362

ignore_unavailable: Optional[bool] = None,

363

allow_no_indices: Optional[bool] = None,

364

expand_wildcards: Optional[str] = None,

365

**kwargs

366

) -> ObjectApiResponse:

367

"""

368

Evaluate search result quality.

369

370

Parameters:

371

- requests: List of search requests with relevance judgments

372

- metric: Evaluation metric configuration

373

- index: Index name(s) to evaluate against

374

- ignore_unavailable: Whether to ignore unavailable indices

375

- allow_no_indices: Whether empty index list is acceptable

376

- expand_wildcards: How to expand wildcard patterns

377

378

Returns:

379

ObjectApiResponse with evaluation results

380

"""

381

```

382

383

### Terms Enumeration

384

385

Enumerate terms from field indices for autocomplete and suggestion features.

386

387

```python { .api }

388

def terms_enum(

389

self,

390

index: str,

391

field: str,

392

size: Optional[int] = None,

393

timeout: Optional[str] = None,

394

case_insensitive: Optional[bool] = None,

395

index_filter: Optional[Dict[str, Any]] = None,

396

string: Optional[str] = None,

397

search_after: Optional[str] = None,

398

**kwargs

399

) -> ObjectApiResponse:

400

"""

401

Enumerate terms from a field.

402

403

Parameters:

404

- index: Index name

405

- field: Field name to get terms from

406

- size: Maximum number of terms to return

407

- timeout: Request timeout

408

- case_insensitive: Whether matching is case insensitive

409

- index_filter: Filter to apply to documents

410

- string: String prefix to match terms

411

- search_after: Term to search after for pagination

412

413

Returns:

414

ObjectApiResponse with enumerated terms

415

"""

416

```

417

418

## Usage Examples

419

420

### Complex Search with Aggregations

421

422

```python

423

from elasticsearch import Elasticsearch

424

425

client = Elasticsearch(hosts=['http://localhost:9200'])

426

427

# Complex search with query, aggregations, and sorting

428

response = client.search(

429

index="products",

430

query={

431

"bool": {

432

"must": [

433

{"match": {"description": "laptop"}},

434

{"range": {"price": {"gte": 500, "lte": 2000}}}

435

],

436

"filter": [

437

{"term": {"status": "active"}}

438

]

439

}

440

},

441

aggs={

442

"price_ranges": {

443

"range": {

444

"field": "price",

445

"ranges": [

446

{"to": 1000},

447

{"from": 1000, "to": 1500},

448

{"from": 1500}

449

]

450

}

451

},

452

"brands": {

453

"terms": {

454

"field": "brand.keyword",

455

"size": 10

456

}

457

}

458

},

459

sort=[

460

{"price": "asc"},

461

"_score"

462

],

463

size=20,

464

from_=0

465

)

466

467

# Process results

468

for hit in response.body['hits']['hits']:

469

print(f"Product: {hit['_source']['name']}, Price: {hit['_source']['price']}")

470

471

# Process aggregations

472

for bucket in response.body['aggregations']['brands']['buckets']:

473

print(f"Brand: {bucket['key']}, Count: {bucket['doc_count']}")

474

```

475

476

### Scroll Search for Large Result Sets

477

478

```python

479

# Initial search with scroll

480

response = client.search(

481

index="logs",

482

query={"match_all": {}},

483

scroll='5m',

484

size=1000

485

)

486

487

scroll_id = response.body['_scroll_id']

488

hits = response.body['hits']['hits']

489

490

# Process initial batch

491

for hit in hits:

492

process_log_entry(hit['_source'])

493

494

# Continue scrolling

495

while hits:

496

response = client.scroll(

497

scroll_id=scroll_id,

498

scroll='5m'

499

)

500

501

scroll_id = response.body['_scroll_id']

502

hits = response.body['hits']['hits']

503

504

for hit in hits:

505

process_log_entry(hit['_source'])

506

507

# Clean up scroll context

508

client.clear_scroll(scroll_id=scroll_id)

509

```

510

511

### Search Template Usage

512

513

```python

514

# Store a search template

515

client.put_script(

516

id="product_search_template",

517

script={

518

"lang": "mustache",

519

"source": {

520

"query": {

521

"bool": {

522

"must": [

523

{"match": {"description": "{{search_term}}"}}

524

],

525

"filter": [

526

{"range": {"price": {"gte": "{{min_price}}", "lte": "{{max_price}}"}}}

527

]

528

}

529

},

530

"size": "{{size}}",

531

"sort": [{"{{sort_field}}": "{{sort_order}}"}]

532

}

533

}

534

)

535

536

# Use the template

537

response = client.search_template(

538

index="products",

539

id="product_search_template",

540

params={

541

"search_term": "laptop",

542

"min_price": 500,

543

"max_price": 2000,

544

"size": 10,

545

"sort_field": "price",

546

"sort_order": "asc"

547

}

548

)

549

```