Completed
Pull Request — master (#1859)
by
unknown
05:58 queued 02:17
created

IndexTest::testAddRemoveAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Elastica\Test;
4
5
use Elastica\Document;
6
use Elastica\Exception\InvalidException;
7
use Elastica\Exception\ResponseException;
8
use Elastica\Index;
9
use Elastica\Mapping;
10
use Elastica\Query\QueryString;
11
use Elastica\Query\SimpleQueryString;
12
use Elastica\Query\Term;
13
use Elastica\Request;
14
use Elastica\Script\Script;
15
use Elastica\Status;
16
use Elastica\Test\Base as BaseTest;
17
use Elasticsearch\Endpoints\Indices\Analyze;
18
19
/**
20
 * @group functional
21
 *
22
 * @internal
23
 */
24
class IndexTest extends BaseTest
25
{
26
    public function testMapping(): void
27
    {
28
        $index = $this->_createIndex();
29
30
        $mappings = new Mapping([
31
            'id' => ['type' => 'integer', 'store' => true],
32
            'email' => ['type' => 'text'],
33
            'username' => ['type' => 'text'],
34
            'test' => ['type' => 'integer'],
35
        ]);
36
        $index->setMapping($mappings);
37
        $index->addDocument(
38
            new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'hanswurst', 'test' => ['2', '3', '5']])
39
        );
40
        $index->forcemerge();
41
42
        $storedMapping = $index->getMapping();
43
44
        $this->assertEquals('integer', $storedMapping['properties']['id']['type']);
45
        $this->assertEquals(true, $storedMapping['properties']['id']['store']);
46
        $this->assertEquals('text', $storedMapping['properties']['email']['type']);
47
        $this->assertEquals('text', $storedMapping['properties']['username']['type']);
48
        $this->assertEquals('integer', $storedMapping['properties']['test']['type']);
49
    }
50
51
    public function testGetMappingAlias(): void
52
    {
53
        $index = $this->_createIndex();
54
        $indexName = $index->getName();
55
56
        $aliasName = 'test-mapping-alias';
57
        $index->addAlias($aliasName);
58
59
        $mapping = new Mapping(['id' => ['type' => 'integer', 'store' => 'true']]);
60
        $index->setMapping($mapping);
61
62
        $client = $index->getClient();
63
64
        // Index mapping
65
        $mapping1 = $client->getIndex($indexName)->getMapping();
66
67
        // Alias mapping
68
        $mapping2 = $client->getIndex($aliasName)->getMapping();
69
70
        // Make sure, a mapping is set
71
        $this->assertNotEmpty($mapping1);
72
73
        // Alias and index mapping should be identical
74
        $this->assertEquals($mapping1, $mapping2);
75
    }
76
77
    public function testAddRemoveAlias(): void
78
    {
79
        $this->expectException(ResponseException::class);
80
81
        $client = $this->_getClient();
82
83
        $indexName1 = 'test1';
84
        $aliasName = 'test-alias';
85
        $typeName = 'test';
0 ignored issues
show
Unused Code introduced by
$typeName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
86
87
        $index = $client->getIndex($indexName1);
88
        $index->create(['settings' => ['index' => ['number_of_shards' => 1, 'number_of_replicas' => 0]]], true);
89
        $index->addDocument(new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'ruflin']));
90
        $index->refresh();
91
92
        $resultSet = $index->search('ruflin');
93
        $this->assertEquals(1, $resultSet->count());
94
95
        $data = $index->addAlias($aliasName, true)->getData();
96
        $this->assertTrue($data['acknowledged']);
97
98
        $response = $index->removeAlias($aliasName)->getData();
99
        $this->assertTrue($response['acknowledged']);
100
101
        $client->getIndex($aliasName)->search('ruflin');
102
    }
103
104 View Code Duplication
    public function testCount(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        $index = $this->_createIndex();
107
108
        // Add document to normal index
109
        $doc1 = new Document(null, ['name' => 'ruflin']);
110
        $doc2 = new Document(null, ['name' => 'nicolas']);
111
112
        $index->addDocument($doc1);
113
        $index->addDocument($doc2);
114
115
        $index->refresh();
116
117
        $this->assertEquals(2, $index->count());
118
119
        $query = new Term();
120
        $key = 'name';
121
        $value = 'nicolas';
122
        $query->setTerm($key, $value);
123
124
        $this->assertEquals(1, $index->count($query));
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Query\Term>, but the function expects a string|array|object<Elastica\Query>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
125
    }
126
127 View Code Duplication
    public function testCountGet(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
    {
129
        $index = $this->_createIndex();
130
131
        // Add document to normal index
132
        $doc1 = new Document(null, ['name' => 'ruflin']);
133
        $doc2 = new Document(null, ['name' => 'nicolas']);
134
135
        $index->addDocument($doc1);
136
        $index->addDocument($doc2);
137
138
        $index->refresh();
139
140
        $this->assertEquals(2, $index->count('', Request::GET));
141
142
        $query = new Term();
143
        $key = 'name';
144
        $value = 'nicolas';
145
        $query->setTerm($key, $value);
146
147
        $this->assertEquals(1, $index->count($query, Request::GET));
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Query\Term>, but the function expects a string|array|object<Elastica\Query>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
148
    }
149
150 View Code Duplication
    public function testDeleteByQueryWithQueryString(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
    {
152
        $index = $this->_createIndex();
153
        $index->addDocuments([
154
            new Document(1, ['name' => 'ruflin nicolas']),
155
            new Document(2, ['name' => 'ruflin']),
156
        ]);
157
        $index->refresh();
158
159
        $response = $index->search('ruflin*');
160
        $this->assertEquals(2, $response->count());
161
162
        $response = $index->search('nicolas');
163
        $this->assertEquals(1, $response->count());
164
165
        // Delete first document
166
        $response = $index->deleteByQuery('nicolas');
167
        $this->assertTrue($response->isOk());
168
169
        $index->refresh();
170
171
        // Makes sure, document is deleted
172
        $response = $index->search('ruflin*');
173
        $this->assertEquals(1, $response->count());
174
175
        $response = $index->search('nicolas');
176
        $this->assertEquals(0, $response->count());
177
    }
178
179 View Code Duplication
    public function testDeleteByQueryWithQuery(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
180
    {
181
        $index = $this->_createIndex();
182
        $index->addDocuments([
183
            new Document(1, ['name' => 'ruflin nicolas']),
184
            new Document(2, ['name' => 'ruflin']),
185
        ]);
186
        $index->refresh();
187
188
        $response = $index->search('ruflin*');
189
        $this->assertEquals(2, $response->count());
190
191
        $response = $index->search('nicolas');
192
        $this->assertEquals(1, $response->count());
193
194
        // Delete first document
195
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'));
196
        $this->assertTrue($response->isOk());
197
198
        $index->refresh();
199
200
        // Makes sure, document is deleted
201
        $response = $index->search('ruflin*');
202
        $this->assertEquals(1, $response->count());
203
204
        $response = $index->search('nicolas');
205
        $this->assertEquals(0, $response->count());
206
    }
207
208
    public function testDeleteByQueryWithArrayQuery(): void
209
    {
210
        $index = $this->_createIndex();
211
        $index->addDocuments([
212
            new Document(1, ['name' => 'ruflin nicolas']),
213
            new Document(2, ['name' => 'ruflin']),
214
        ]);
215
        $index->refresh();
216
217
        $response = $index->search('ruflin*');
218
        $this->assertEquals(2, $response->count());
219
220
        $response = $index->search('nicolas');
221
        $this->assertEquals(1, $response->count());
222
223
        // Delete first document
224
        $response = $index->deleteByQuery(['query' => ['query_string' => ['query' => 'nicolas']]]);
225
        $this->assertTrue($response->isOk());
226
227
        $index->refresh();
228
229
        // Makes sure, document is deleted
230
        $response = $index->search('ruflin*');
231
        $this->assertEquals(1, $response->count());
232
233
        $response = $index->search('nicolas');
234
        $this->assertEquals(0, $response->count());
235
    }
236
237
    public function testDeleteByQueryWithQueryAndOptions(): void
238
    {
239
        $index = $this->_createIndex(null, true, 2);
240
241
        $routing1 = 'first_routing';
242
        $routing2 = 'second_routing';
243
244
        $doc = new Document(1, ['name' => 'ruflin nicolas']);
245
        $doc->setRouting($routing1);
246
        $index->addDocument($doc);
247
248
        $doc = new Document(2, ['name' => 'ruflin']);
249
        $doc->setRouting($routing1);
250
        $index->addDocument($doc);
251
252
        $doc = new Document(2, ['name' => 'ruflin']);
253
        $doc->setRouting($routing1);
254
        $index->addDocument($doc);
255
256
        $index->refresh();
257
258
        $response = $index->search('ruflin*');
259
        $this->assertEquals(2, $response->count());
260
261
        $response = $index->search('ruflin*', ['routing' => $routing2]);
262
        $this->assertEquals(0, $response->count());
263
264
        $response = $index->search('nicolas');
265
        $this->assertEquals(1, $response->count());
266
267
        // Route to the wrong document id; should not delete
268
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'), ['routing' => $routing2]);
269
        $this->assertTrue($response->isOk());
270
271
        $index->refresh();
272
273
        $response = $index->search('ruflin*');
274
        $this->assertEquals(2, $response->count());
275
276
        $response = $index->search('nicolas');
277
        $this->assertEquals(1, $response->count());
278
279
        // Delete first document
280
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'), ['routing' => $routing1]);
281
        $this->assertTrue($response->isOk());
282
283
        $index->refresh();
284
285
        // Makes sure, document is deleted
286
        $response = $index->search('ruflin*');
287
        $this->assertEquals(1, $response->count());
288
289
        $response = $index->search('nicolas');
290
        $this->assertEquals(0, $response->count());
291
    }
292
293 View Code Duplication
    public function testUpdateByQueryWithQueryString(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
294
    {
295
        $index = $this->_createIndex();
296
        $index->addDocuments([
297
            new Document(1, ['name' => 'ruflin nicolas']),
298
            new Document(2, ['name' => 'ruflin']),
299
        ]);
300
        $index->refresh();
301
302
        $response = $index->search('ruflin*');
303
        $this->assertEquals(2, $response->count());
304
305
        $response = $index->search('nicolas');
306
        $this->assertEquals(1, $response->count());
307
308
        // Update the element, searched by specific word. Should match first one
309
        $response = $index->updateByQuery('nicolas', new Script('ctx._source.name = "marc"'));
310
        $this->assertTrue($response->isOk());
311
312
        $index->refresh();
313
314
        // Makes sure first element is updated and renamed to marc. Should match only second
315
        $response = $index->search('ruflin*');
316
        $this->assertEquals(1, $response->count());
317
318
        $response = $index->search('marc*');
319
        $this->assertEquals(1, $response->count());
320
321
        $response = $index->search('nicolas');
322
        $this->assertEquals(0, $response->count());
323
    }
324
325 View Code Duplication
    public function testUpdateByQueryAll(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
326
    {
327
        $index = $this->_createIndex();
328
        $index->addDocuments([
329
            new Document(1, ['name' => 'ruflin nicolas']),
330
            new Document(2, ['name' => 'ruflin']),
331
        ]);
332
        $index->refresh();
333
334
        $response = $index->search('ruflin*');
335
        $this->assertEquals(2, $response->count());
336
337
        $response = $index->search('nicolas');
338
        $this->assertEquals(1, $response->count());
339
340
        // Update all elements to name "marc"
341
        $response = $index->updateByQuery('*', new Script('ctx._source.name = "marc"'));
342
        $this->assertTrue($response->isOk());
343
344
        $index->refresh();
345
346
        // Because all documents have changed to marc, searching by "ruflin*" should match 0
347
        $response = $index->search('ruflin*');
348
        $this->assertEquals(0, $response->count());
349
350
        $response = $index->search('marc');
351
        $this->assertEquals(2, $response->count());
352
353
        $response = $index->search('nicolas');
354
        $this->assertEquals(0, $response->count());
355
    }
356
357
    public function testDeleteIndexDeleteAlias(): void
358
    {
359
        $indexName = 'test';
360
        $aliasName = 'test-aliase';
361
362
        $client = $this->_getClient();
363
        $index = $client->getIndex($indexName);
364
365
        $index->create([], true);
366
        $index->addAlias($aliasName);
367
368
        $status = new Status($client);
369
        $this->assertTrue($status->indexExists($indexName));
370
        $this->assertTrue($status->aliasExists($aliasName));
371
372
        // Deleting index should also remove alias
373
        $index->delete();
374
375
        $status->refresh();
376
        $this->assertFalse($status->indexExists($indexName));
377
        $this->assertFalse($status->aliasExists($aliasName));
378
    }
379
380 View Code Duplication
    public function testAddAliasTwoIndices(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
381
    {
382
        $indexName1 = 'test1';
383
        $aliasName = 'test-alias';
384
385
        $client = $this->_getClient();
386
        $index1 = $client->getIndex($indexName1);
387
388
        $index1->create([], true);
389
        $this->_waitForAllocation($index1);
390
        $index1->addAlias($aliasName);
391
392
        $index1->refresh();
393
        $index1->forcemerge();
394
395
        $status = new Status($client);
396
397
        $this->assertTrue($status->indexExists($indexName1));
398
399
        $this->assertTrue($status->aliasExists($aliasName));
400
        $this->assertTrue($index1->hasAlias($aliasName));
401
    }
402
403 View Code Duplication
    public function testReplaceAlias(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
404
    {
405
        $indexName1 = 'test1';
406
        $aliasName = 'test-alias';
407
408
        $client = $this->_getClient();
409
        $index1 = $client->getIndex($indexName1);
410
411
        $index1->create([], true);
412
        $index1->addAlias($aliasName);
413
414
        $index1->refresh();
415
416
        $status = new Status($client);
417
418
        $this->assertTrue($status->indexExists($indexName1));
419
        $this->assertTrue($status->aliasExists($aliasName));
420
        $this->assertTrue($index1->hasAlias($aliasName));
421
    }
422
423
    public function testAddDocumentVersion(): void
424
    {
425
        $client = $this->_getClient();
426
        $index = $client->getIndex('test');
427
        $index->create([], true);
428
429
        $doc1 = new Document(1);
430
        $doc1->set('title', 'Hello world');
431
432
        $return = $index->addDocument($doc1);
433
        $data = $return->getData();
434
        $this->assertEquals(1, $data['_version']);
435
436
        $return = $index->addDocument($doc1);
437
        $data = $return->getData();
438
        $this->assertEquals(2, $data['_version']);
439
    }
440
441
    public function testClearCache(): void
442
    {
443
        $index = $this->_createIndex();
444
        $response = $index->clearCache();
445
        $this->assertFalse($response->hasError());
446
    }
447
448
    public function testFlush(): void
449
    {
450
        $index = $this->_createIndex();
451
        $response = $index->flush();
452
        $this->assertFalse($response->hasError());
453
    }
454
455
    public function testExists(): void
456
    {
457
        $index = $this->_createIndex();
458
459
        $this->assertTrue($index->exists());
460
461
        $index->delete();
462
463
        $this->assertFalse($index->exists());
464
    }
465
466
    /**
467
     * Test $index->delete() return value for unknown index.
468
     *
469
     * Tests if deleting an index that does not exist in Elasticsearch,
470
     * correctly returns a boolean true from the hasError() method of
471
     * the \Elastica\Response object
472
     */
473 View Code Duplication
    public function testDeleteMissingIndexHasError(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
474
    {
475
        $client = $this->_getClient();
476
        $index = $client->getIndex('index_does_not_exist');
477
478
        try {
479
            $index->delete();
480
            $this->fail('This should never be reached. Deleting an unknown index will throw an exception');
481
        } catch (ResponseException $error) {
482
            $response = $error->getResponse();
483
            $this->assertTrue($response->hasError());
484
            $request = $error->getRequest();
485
            $this->assertInstanceOf(Request::class, $request);
486
        }
487
    }
488
489
    /**
490
     * Tests to see if the test type mapping exists when calling $index->getMapping().
491
     */
492
    public function testIndexGetMapping(): void
493
    {
494
        $index = $this->_createIndex();
495
        $mappings = new Mapping([
496
            'id' => ['type' => 'integer', 'store' => true],
497
            'email' => ['type' => 'text'],
498
            'username' => ['type' => 'text'],
499
            'test' => ['type' => 'integer'],
500
        ]);
501
502
        $index->setMapping($mappings);
503
        $index->refresh();
504
        $indexMappings = $index->getMapping();
505
506
        $this->assertEquals('integer', $indexMappings['properties']['id']['type']);
507
        $this->assertEquals(true, $indexMappings['properties']['id']['store']);
508
        $this->assertEquals('text', $indexMappings['properties']['email']['type']);
509
        $this->assertEquals('text', $indexMappings['properties']['username']['type']);
510
        $this->assertEquals('integer', $indexMappings['properties']['test']['type']);
511
    }
512
513
    public function testEmptyIndexGetMapping(): void
514
    {
515
        $indexMappings = $this->_createIndex()->getMapping();
516
517
        $this->assertEmpty($indexMappings);
518
    }
519
520
    /**
521
     * Test to see if search Default Limit works.
522
     */
523
    public function testLimitDefaultIndex(): void
524
    {
525
        $client = $this->_getClient();
526
        $index = $client->getIndex('zero');
527
        $index->create(['settings' => ['index' => ['number_of_shards' => 1, 'number_of_replicas' => 0]]]);
528
529
        $docs = [
530
            new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
531
            new Document(2, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
532
            new Document(3, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
533
            new Document(4, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
534
            new Document(5, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
535
            new Document(6, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
536
            new Document(7, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
537
            new Document(8, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
538
            new Document(9, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
539
            new Document(10, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
540
            new Document(11, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
541
        ];
542
        $index->addDocuments($docs);
543
        $index->refresh();
544
545
        // default limit results  (default limit is 10)
546
        $resultSet = $index->search('farrelley');
547
        $this->assertEquals(10, $resultSet->count());
548
549
        // limit = 1
550
        $resultSet = $index->search('farrelley', 1);
551
        $this->assertEquals(1, $resultSet->count());
552
    }
553
554
    public function testCreate(): void
555
    {
556
        $client = $this->_getClient();
557
        $indexName = 'test';
558
559
        //Testing recreate (backward compatibility)
560
        $index = $client->getIndex($indexName);
561
        $index->create([], true);
562
        $this->_waitForAllocation($index);
563
        $status = new Status($client);
564
        $this->assertTrue($status->indexExists($indexName));
565
566
        //Testing create index with array options
567
        $opts = ['recreate' => true];
568
        $index->create([], $opts);
569
        $this->_waitForAllocation($index);
570
        $status = new Status($client);
571
        $this->assertTrue($status->indexExists($indexName));
572
    }
573
574
    /**
575
     * @group unit
576
     */
577
    public function testCreateWithEndpointOption(): void
578
    {
579
        $client = $this->_getClient();
580
        $indexName = 'test';
581
        $index = $client->getIndex($indexName);
582
583
        $opts = ['wait_for_active_shards' => 1];
584
        $index->create([], $opts);
585
    }
586
587
    /**
588
     * @group unit
589
     */
590
    public function testCreateWithInvalidOption(): void
591
    {
592
        $this->expectException(InvalidException::class);
593
        $this->expectExceptionMessage('"testing_invalid_option" is not a valid option. Allowed options are "recreate".');
594
595
        $client = $this->_getClient();
596
        $indexName = 'test';
597
        $index = $client->getIndex($indexName);
598
599
        $opts = ['testing_invalid_option' => true];
600
        $index->create([], $opts);
601
    }
602
603
    public function testCreateSearch(): void
604
    {
605
        $client = $this->_getClient();
606
        $index = new Index($client, 'test');
607
608
        $query = new QueryString('test');
609
        $options = 5;
610
611
        $search = $index->createSearch($query, $options);
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Query\QueryString>, but the function expects a string|array|object<Elastica\Query>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
612
613
        $expected = [
614
            'query' => [
615
                'query_string' => [
616
                    'query' => 'test',
617
                ],
618
            ],
619
            'size' => 5,
620
        ];
621
        $this->assertEquals($expected, $search->getQuery()->toArray());
622
        $this->assertEquals(['test'], $search->getIndices());
623
        $this->assertTrue($search->hasIndices());
624
        $this->assertTrue($search->hasIndex('test'));
625
        $this->assertTrue($search->hasIndex($index));
626
    }
627
628
    public function testSearch(): void
629
    {
630
        $index = $this->_createIndex();
631
632
        $docs = [];
633
        $docs[] = new Document(1, ['username' => 'hans', 'test' => ['2', '3', '5']]);
634
        $docs[] = new Document(2, ['username' => 'john', 'test' => ['1', '3', '6']]);
635
        $docs[] = new Document(3, ['username' => 'rolf', 'test' => ['2', '3', '7']]);
636
        $index->addDocuments($docs);
637
        $index->refresh();
638
639
        $resultSet = $index->search('rolf');
640
        $this->assertEquals(1, $resultSet->count());
641
642
        $count = $index->count('rolf');
643
        $this->assertEquals(1, $count);
644
645
        // Test if source is returned
646
        $result = $resultSet->current();
647
        $this->assertEquals(3, $result->getId());
648
        $data = $result->getData();
649
        $this->assertEquals('rolf', $data['username']);
650
651
        $count = $index->count();
652
        $this->assertEquals(3, $count);
653
    }
654
655
    public function testSearchGet(): void
656
    {
657
        $index = $this->_createIndex();
658
        $docs = [];
659
        $docs[] = new Document(1, ['username' => 'hans']);
660
        $index->addDocuments($docs);
661
        $index->refresh();
662
663
        $resultSet = $index->search('hans', null, Request::GET);
664
        $this->assertEquals(1, $resultSet->count());
665
666
        $count = $index->count('hans', Request::GET);
667
        $this->assertEquals(1, $count);
668
    }
669
670
    public function testForcemerge(): void
671
    {
672
        $index = $this->_createIndex('testforcemerge_indextest', false, 3);
673
674
        $docs = [];
675
        $docs[] = new Document(1, ['foo' => 'bar']);
676
        $docs[] = new Document(2, ['foo' => 'bar']);
677
        $index->addDocuments($docs);
678
        $index->refresh();
679
680
        $stats = $index->getStats()->getData();
681
        $this->assertEquals(2, $stats['_all']['primaries']['docs']['count']);
682
        $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']);
683
684
        $index->deleteById('1');
685
        $index->refresh();
686
687
        $stats = $index->getStats()->getData();
688
        $this->assertEquals(1, $stats['_all']['primaries']['docs']['count']);
689
690
        $index->forcemerge(['max_num_segments' => 1]);
691
692
        $stats = $index->getStats()->getData();
693
        $this->assertEquals(1, $stats['_all']['primaries']['docs']['count']);
694
        $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']);
695
    }
696
697
    public function testAnalyze(): void
698
    {
699
        $index = $this->_createIndex();
700
        $index->refresh();
701
        $returnedTokens = $index->analyze(['text' => 'foo']);
702
703
        $tokens = [
704
            [
705
                'token' => 'foo',
706
                'start_offset' => 0,
707
                'end_offset' => 3,
708
                'type' => '<ALPHANUM>',
709
                'position' => 0,
710
            ],
711
        ];
712
713
        $this->assertEquals($tokens, $returnedTokens);
714
    }
715
716
    public function testRequestEndpoint(): void
717
    {
718
        $index = $this->_createIndex();
719
        $index->refresh();
720
        $endpoint = new Analyze();
721
        $endpoint->setIndex('fooIndex');
722
        $endpoint->setBody(['text' => 'foo']);
723
        $returnedTokens = $index->requestEndpoint($endpoint)->getData()['tokens'];
724
725
        $tokens = [
726
            [
727
                'token' => 'foo',
728
                'start_offset' => 0,
729
                'end_offset' => 3,
730
                'type' => '<ALPHANUM>',
731
                'position' => 0,
732
            ],
733
        ];
734
735
        $this->assertEquals($tokens, $returnedTokens);
736
    }
737
738
    public function testAnalyzeExplain(): void
739
    {
740
        $index = $this->_createIndex();
741
        $index->refresh();
742
        $data = $index->analyze(['text' => 'foo', 'explain' => true], []);
743
744
        $this->assertArrayHasKey('custom_analyzer', $data);
745
    }
746
747
    public function testGetEmptyAliases(): void
748
    {
749
        $indexName = 'test-getaliases';
750
751
        $client = $this->_getClient();
752
        $index = $client->getIndex($indexName);
753
754
        $index->create([], true);
755
        $this->_waitForAllocation($index);
756
        $index->refresh();
757
        $index->forcemerge();
758
759
        $this->assertEquals([], $index->getAliases());
760
    }
761
}
762