Completed
Pull Request — master (#1867)
by
unknown
03:32
created

IndexTest::testLegacyCreate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
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
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
19
20
/**
21
 * @group functional
22
 *
23
 * @internal
24
 */
25
class IndexTest extends BaseTest
26
{
27
    use ExpectDeprecationTrait;
28
29
    public function testMapping(): void
30
    {
31
        $index = $this->_createIndex();
32
33
        $mappings = new Mapping([
34
            'id' => ['type' => 'integer', 'store' => true],
35
            'email' => ['type' => 'text'],
36
            'username' => ['type' => 'text'],
37
            'test' => ['type' => 'integer'],
38
        ]);
39
        $index->setMapping($mappings);
40
        $index->addDocument(
41
            new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'hanswurst', 'test' => ['2', '3', '5']])
42
        );
43
        $index->forcemerge();
44
45
        $storedMapping = $index->getMapping();
46
47
        $this->assertEquals('integer', $storedMapping['properties']['id']['type']);
48
        $this->assertEquals(true, $storedMapping['properties']['id']['store']);
49
        $this->assertEquals('text', $storedMapping['properties']['email']['type']);
50
        $this->assertEquals('text', $storedMapping['properties']['username']['type']);
51
        $this->assertEquals('integer', $storedMapping['properties']['test']['type']);
52
    }
53
54
    public function testGetMappingAlias(): void
55
    {
56
        $index = $this->_createIndex();
57
        $indexName = $index->getName();
58
59
        $aliasName = 'test-mapping-alias';
60
        $index->addAlias($aliasName);
61
62
        $mapping = new Mapping(['id' => ['type' => 'integer', 'store' => 'true']]);
63
        $index->setMapping($mapping);
64
65
        $client = $index->getClient();
66
67
        // Index mapping
68
        $mapping1 = $client->getIndex($indexName)->getMapping();
69
70
        // Alias mapping
71
        $mapping2 = $client->getIndex($aliasName)->getMapping();
72
73
        // Make sure, a mapping is set
74
        $this->assertNotEmpty($mapping1);
75
76
        // Alias and index mapping should be identical
77
        $this->assertEquals($mapping1, $mapping2);
78
    }
79
80
    public function testAddRemoveAlias(): void
81
    {
82
        $this->expectException(ResponseException::class);
83
84
        $client = $this->_getClient();
85
86
        $indexName1 = 'test1';
87
        $aliasName = 'test-alias';
88
89
        $index = $client->getIndex($indexName1);
90
        $index->create(
91
            [
92
                'settings' => [
93
                    'index' => [
94
                        'number_of_shards' => 1,
95
                        'number_of_replicas' => 0,
96
                    ],
97
                ],
98
            ],
99
            [
100
                'recreate' => true,
101
            ]
102
        );
103
        $index->addDocument(new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'ruflin']));
104
        $index->refresh();
105
106
        $resultSet = $index->search('ruflin');
107
        $this->assertEquals(1, $resultSet->count());
108
109
        $data = $index->addAlias($aliasName, true)->getData();
110
        $this->assertTrue($data['acknowledged']);
111
112
        $response = $index->removeAlias($aliasName)->getData();
113
        $this->assertTrue($response['acknowledged']);
114
115
        $client->getIndex($aliasName)->search('ruflin');
116
    }
117
118 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...
119
    {
120
        $index = $this->_createIndex();
121
122
        // Add document to normal index
123
        $doc1 = new Document(null, ['name' => 'ruflin']);
124
        $doc2 = new Document(null, ['name' => 'nicolas']);
125
126
        $index->addDocument($doc1);
127
        $index->addDocument($doc2);
128
129
        $index->refresh();
130
131
        $this->assertEquals(2, $index->count());
132
133
        $query = new Term();
134
        $key = 'name';
135
        $value = 'nicolas';
136
        $query->setTerm($key, $value);
137
138
        $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...
139
    }
140
141 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...
142
    {
143
        $index = $this->_createIndex();
144
145
        // Add document to normal index
146
        $doc1 = new Document(null, ['name' => 'ruflin']);
147
        $doc2 = new Document(null, ['name' => 'nicolas']);
148
149
        $index->addDocument($doc1);
150
        $index->addDocument($doc2);
151
152
        $index->refresh();
153
154
        $this->assertEquals(2, $index->count('', Request::GET));
155
156
        $query = new Term();
157
        $key = 'name';
158
        $value = 'nicolas';
159
        $query->setTerm($key, $value);
160
161
        $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...
162
    }
163
164 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...
165
    {
166
        $index = $this->_createIndex();
167
        $index->addDocuments([
168
            new Document(1, ['name' => 'ruflin nicolas']),
169
            new Document(2, ['name' => 'ruflin']),
170
        ]);
171
        $index->refresh();
172
173
        $response = $index->search('ruflin*');
174
        $this->assertEquals(2, $response->count());
175
176
        $response = $index->search('nicolas');
177
        $this->assertEquals(1, $response->count());
178
179
        // Delete first document
180
        $response = $index->deleteByQuery('nicolas');
181
        $this->assertTrue($response->isOk());
182
183
        $index->refresh();
184
185
        // Makes sure, document is deleted
186
        $response = $index->search('ruflin*');
187
        $this->assertEquals(1, $response->count());
188
189
        $response = $index->search('nicolas');
190
        $this->assertEquals(0, $response->count());
191
    }
192
193 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...
194
    {
195
        $index = $this->_createIndex();
196
        $index->addDocuments([
197
            new Document(1, ['name' => 'ruflin nicolas']),
198
            new Document(2, ['name' => 'ruflin']),
199
        ]);
200
        $index->refresh();
201
202
        $response = $index->search('ruflin*');
203
        $this->assertEquals(2, $response->count());
204
205
        $response = $index->search('nicolas');
206
        $this->assertEquals(1, $response->count());
207
208
        // Delete first document
209
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'));
210
        $this->assertTrue($response->isOk());
211
212
        $index->refresh();
213
214
        // Makes sure, document is deleted
215
        $response = $index->search('ruflin*');
216
        $this->assertEquals(1, $response->count());
217
218
        $response = $index->search('nicolas');
219
        $this->assertEquals(0, $response->count());
220
    }
221
222
    public function testDeleteByQueryWithArrayQuery(): void
223
    {
224
        $index = $this->_createIndex();
225
        $index->addDocuments([
226
            new Document(1, ['name' => 'ruflin nicolas']),
227
            new Document(2, ['name' => 'ruflin']),
228
        ]);
229
        $index->refresh();
230
231
        $response = $index->search('ruflin*');
232
        $this->assertEquals(2, $response->count());
233
234
        $response = $index->search('nicolas');
235
        $this->assertEquals(1, $response->count());
236
237
        // Delete first document
238
        $response = $index->deleteByQuery(['query' => ['query_string' => ['query' => 'nicolas']]]);
239
        $this->assertTrue($response->isOk());
240
241
        $index->refresh();
242
243
        // Makes sure, document is deleted
244
        $response = $index->search('ruflin*');
245
        $this->assertEquals(1, $response->count());
246
247
        $response = $index->search('nicolas');
248
        $this->assertEquals(0, $response->count());
249
    }
250
251
    public function testDeleteByQueryWithQueryAndOptions(): void
252
    {
253
        $index = $this->_createIndex(null, true, 2);
254
255
        $routing1 = 'first_routing';
256
        $routing2 = 'second_routing';
257
258
        $doc = new Document(1, ['name' => 'ruflin nicolas']);
259
        $doc->setRouting($routing1);
260
        $index->addDocument($doc);
261
262
        $doc = new Document(2, ['name' => 'ruflin']);
263
        $doc->setRouting($routing1);
264
        $index->addDocument($doc);
265
266
        $doc = new Document(2, ['name' => 'ruflin']);
267
        $doc->setRouting($routing1);
268
        $index->addDocument($doc);
269
270
        $index->refresh();
271
272
        $response = $index->search('ruflin*');
273
        $this->assertEquals(2, $response->count());
274
275
        $response = $index->search('ruflin*', ['routing' => $routing2]);
276
        $this->assertEquals(0, $response->count());
277
278
        $response = $index->search('nicolas');
279
        $this->assertEquals(1, $response->count());
280
281
        // Route to the wrong document id; should not delete
282
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'), ['routing' => $routing2]);
283
        $this->assertTrue($response->isOk());
284
285
        $index->refresh();
286
287
        $response = $index->search('ruflin*');
288
        $this->assertEquals(2, $response->count());
289
290
        $response = $index->search('nicolas');
291
        $this->assertEquals(1, $response->count());
292
293
        // Delete first document
294
        $response = $index->deleteByQuery(new SimpleQueryString('nicolas'), ['routing' => $routing1]);
295
        $this->assertTrue($response->isOk());
296
297
        $index->refresh();
298
299
        // Makes sure, document is deleted
300
        $response = $index->search('ruflin*');
301
        $this->assertEquals(1, $response->count());
302
303
        $response = $index->search('nicolas');
304
        $this->assertEquals(0, $response->count());
305
    }
306
307 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...
308
    {
309
        $index = $this->_createIndex();
310
        $index->addDocuments([
311
            new Document(1, ['name' => 'ruflin nicolas']),
312
            new Document(2, ['name' => 'ruflin']),
313
        ]);
314
        $index->refresh();
315
316
        $response = $index->search('ruflin*');
317
        $this->assertEquals(2, $response->count());
318
319
        $response = $index->search('nicolas');
320
        $this->assertEquals(1, $response->count());
321
322
        // Update the element, searched by specific word. Should match first one
323
        $response = $index->updateByQuery('nicolas', new Script('ctx._source.name = "marc"'));
324
        $this->assertTrue($response->isOk());
325
326
        $index->refresh();
327
328
        // Makes sure first element is updated and renamed to marc. Should match only second
329
        $response = $index->search('ruflin*');
330
        $this->assertEquals(1, $response->count());
331
332
        $response = $index->search('marc*');
333
        $this->assertEquals(1, $response->count());
334
335
        $response = $index->search('nicolas');
336
        $this->assertEquals(0, $response->count());
337
    }
338
339 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...
340
    {
341
        $index = $this->_createIndex();
342
        $index->addDocuments([
343
            new Document(1, ['name' => 'ruflin nicolas']),
344
            new Document(2, ['name' => 'ruflin']),
345
        ]);
346
        $index->refresh();
347
348
        $response = $index->search('ruflin*');
349
        $this->assertEquals(2, $response->count());
350
351
        $response = $index->search('nicolas');
352
        $this->assertEquals(1, $response->count());
353
354
        // Update all elements to name "marc"
355
        $response = $index->updateByQuery('*', new Script('ctx._source.name = "marc"'));
356
        $this->assertTrue($response->isOk());
357
358
        $index->refresh();
359
360
        // Because all documents have changed to marc, searching by "ruflin*" should match 0
361
        $response = $index->search('ruflin*');
362
        $this->assertEquals(0, $response->count());
363
364
        $response = $index->search('marc');
365
        $this->assertEquals(2, $response->count());
366
367
        $response = $index->search('nicolas');
368
        $this->assertEquals(0, $response->count());
369
    }
370
371
    public function testDeleteIndexDeleteAlias(): void
372
    {
373
        $indexName = 'test';
374
        $aliasName = 'test-aliase';
375
376
        $client = $this->_getClient();
377
        $index = $client->getIndex($indexName);
378
379
        $index->create([], [
380
            'recreate' => true,
381
        ]);
382
        $index->addAlias($aliasName);
383
384
        $status = new Status($client);
385
        $this->assertTrue($status->indexExists($indexName));
386
        $this->assertTrue($status->aliasExists($aliasName));
387
388
        // Deleting index should also remove alias
389
        $index->delete();
390
391
        $status->refresh();
392
        $this->assertFalse($status->indexExists($indexName));
393
        $this->assertFalse($status->aliasExists($aliasName));
394
    }
395
396 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...
397
    {
398
        $indexName1 = 'test1';
399
        $aliasName = 'test-alias';
400
401
        $client = $this->_getClient();
402
        $index1 = $client->getIndex($indexName1);
403
404
        $index1->create([], [
405
            'recreate' => true,
406
        ]);
407
        $this->_waitForAllocation($index1);
408
        $index1->addAlias($aliasName);
409
410
        $index1->refresh();
411
        $index1->forcemerge();
412
413
        $status = new Status($client);
414
415
        $this->assertTrue($status->indexExists($indexName1));
416
417
        $this->assertTrue($status->aliasExists($aliasName));
418
        $this->assertTrue($index1->hasAlias($aliasName));
419
    }
420
421
    public function testReplaceAlias(): void
422
    {
423
        $indexName1 = 'test1';
424
        $aliasName = 'test-alias';
425
426
        $client = $this->_getClient();
427
        $index1 = $client->getIndex($indexName1);
428
429
        $index1->create([], [
430
            'recreate' => true,
431
        ]);
432
        $index1->addAlias($aliasName);
433
434
        $index1->refresh();
435
436
        $status = new Status($client);
437
438
        $this->assertTrue($status->indexExists($indexName1));
439
        $this->assertTrue($status->aliasExists($aliasName));
440
        $this->assertTrue($index1->hasAlias($aliasName));
441
    }
442
443
    public function testAddDocumentVersion(): void
444
    {
445
        $client = $this->_getClient();
446
        $index = $client->getIndex('test');
447
        $index->create([], [
448
            'recreate' => true,
449
        ]);
450
451
        $doc1 = new Document(1);
452
        $doc1->set('title', 'Hello world');
453
454
        $return = $index->addDocument($doc1);
455
        $data = $return->getData();
456
        $this->assertEquals(1, $data['_version']);
457
458
        $return = $index->addDocument($doc1);
459
        $data = $return->getData();
460
        $this->assertEquals(2, $data['_version']);
461
    }
462
463
    public function testClearCache(): void
464
    {
465
        $index = $this->_createIndex();
466
        $response = $index->clearCache();
467
        $this->assertFalse($response->hasError());
468
    }
469
470
    public function testFlush(): void
471
    {
472
        $index = $this->_createIndex();
473
        $response = $index->flush();
474
        $this->assertFalse($response->hasError());
475
    }
476
477
    public function testExists(): void
478
    {
479
        $index = $this->_createIndex();
480
481
        $this->assertTrue($index->exists());
482
483
        $index->delete();
484
485
        $this->assertFalse($index->exists());
486
    }
487
488
    /**
489
     * Test $index->delete() return value for unknown index.
490
     *
491
     * Tests if deleting an index that does not exist in Elasticsearch,
492
     * correctly returns a boolean true from the hasError() method of
493
     * the \Elastica\Response object
494
     */
495
    public function testDeleteMissingIndexHasError(): void
496
    {
497
        $client = $this->_getClient();
498
        $index = $client->getIndex('index_does_not_exist');
499
500
        try {
501
            $index->delete();
502
            $this->fail('This should never be reached. Deleting an unknown index will throw an exception');
503
        } catch (ResponseException $error) {
504
            $response = $error->getResponse();
505
            $this->assertTrue($response->hasError());
506
            $request = $error->getRequest();
507
            $this->assertInstanceOf(Request::class, $request);
508
        }
509
    }
510
511
    /**
512
     * Tests to see if the test type mapping exists when calling $index->getMapping().
513
     */
514
    public function testIndexGetMapping(): void
515
    {
516
        $index = $this->_createIndex();
517
        $mappings = new Mapping([
518
            'id' => ['type' => 'integer', 'store' => true],
519
            'email' => ['type' => 'text'],
520
            'username' => ['type' => 'text'],
521
            'test' => ['type' => 'integer'],
522
        ]);
523
524
        $index->setMapping($mappings);
525
        $index->refresh();
526
        $indexMappings = $index->getMapping();
527
528
        $this->assertEquals('integer', $indexMappings['properties']['id']['type']);
529
        $this->assertEquals(true, $indexMappings['properties']['id']['store']);
530
        $this->assertEquals('text', $indexMappings['properties']['email']['type']);
531
        $this->assertEquals('text', $indexMappings['properties']['username']['type']);
532
        $this->assertEquals('integer', $indexMappings['properties']['test']['type']);
533
    }
534
535
    public function testEmptyIndexGetMapping(): void
536
    {
537
        $indexMappings = $this->_createIndex()->getMapping();
538
539
        $this->assertEmpty($indexMappings);
540
    }
541
542
    /**
543
     * Test to see if search Default Limit works.
544
     */
545
    public function testLimitDefaultIndex(): void
546
    {
547
        $client = $this->_getClient();
548
        $index = $client->getIndex('zero');
549
        $index->create(['settings' => ['index' => ['number_of_shards' => 1, 'number_of_replicas' => 0]]]);
550
551
        $docs = [
552
            new Document(1, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
553
            new Document(2, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
554
            new Document(3, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
555
            new Document(4, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
556
            new Document(5, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
557
            new Document(6, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
558
            new Document(7, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
559
            new Document(8, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
560
            new Document(9, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
561
            new Document(10, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
562
            new Document(11, ['id' => 1, 'email' => '[email protected]', 'username' => 'farrelley']),
563
        ];
564
        $index->addDocuments($docs);
565
        $index->refresh();
566
567
        // default limit results  (default limit is 10)
568
        $resultSet = $index->search('farrelley');
569
        $this->assertEquals(10, $resultSet->count());
570
571
        // limit = 1
572
        $resultSet = $index->search('farrelley', 1);
573
        $this->assertEquals(1, $resultSet->count());
574
    }
575
576
    /**
577
     * @group functional
578
     */
579 View Code Duplication
    public function testCreate(): 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...
580
    {
581
        $client = $this->_getClient();
582
        $indexName = 'test';
583
584
        $index = $client->getIndex($indexName);
585
        $index->create([]);
586
        $this->_waitForAllocation($index);
587
        $status = new Status($client);
588
        $this->assertTrue($status->indexExists($indexName));
589
590
        $index = $client->getIndex($indexName);
591
        $index->create([], [
592
            'recreate' => true,
593
        ]);
594
        $this->_waitForAllocation($index);
595
        $status = new Status($client);
596
        $this->assertTrue($status->indexExists($indexName));
597
    }
598
599
    /**
600
     * @group functional
601
     * @group legacy
602
     */
603
    public function testLegacyCreate(): void
604
    {
605
        $client = $this->_getClient();
606
        $indexName = 'test';
607
        $index = $client->getIndex($indexName);
608
609
        $this->expectDeprecation('Since ruflin/elastica 7.1.0: Passing null as 2nd argument to "Elastica\Index::create()" is deprecated, avoid passing this argument or pass an array instead. It will be removed in 8.0.');
610
        $index->create([], null);
611
        $this->_waitForAllocation($index);
612
        $status = new Status($client);
613
        $this->assertTrue($status->indexExists($indexName));
614
615
        $this->expectDeprecation('Since ruflin/elastica 7.1.0: Passing a bool as 2nd argument to "Elastica\Index::create()" is deprecated, pass an array with the key "recreate" instead. It will be removed in 8.0.');
616
        $index->create([], true);
617
        $this->_waitForAllocation($index);
618
        $status = new Status($client);
619
        $this->assertTrue($status->indexExists($indexName));
620
    }
621
622
    /**
623
     * @group unit
624
     */
625
    public function testCreateWithInvalidOption(): void
626
    {
627
        $this->expectException(InvalidException::class);
628
        $this->expectExceptionMessage('"testing_invalid_option" is not a valid option. Allowed options are "recreate".');
629
630
        $client = $this->_getClient();
631
        $indexName = 'test';
632
        $index = $client->getIndex($indexName);
633
634
        $opts = ['testing_invalid_option' => true];
635
        $index->create([], $opts);
636
    }
637
638
    public function testCreateSearch(): void
639
    {
640
        $client = $this->_getClient();
641
        $index = new Index($client, 'test');
642
643
        $query = new QueryString('test');
644
        $options = 5;
645
646
        $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...
647
648
        $expected = [
649
            'query' => [
650
                'query_string' => [
651
                    'query' => 'test',
652
                ],
653
            ],
654
            'size' => 5,
655
        ];
656
        $this->assertEquals($expected, $search->getQuery()->toArray());
657
        $this->assertEquals(['test'], $search->getIndices());
658
        $this->assertTrue($search->hasIndices());
659
        $this->assertTrue($search->hasIndex('test'));
660
        $this->assertTrue($search->hasIndex($index));
661
    }
662
663
    public function testSearch(): void
664
    {
665
        $index = $this->_createIndex();
666
667
        $docs = [];
668
        $docs[] = new Document(1, ['username' => 'hans', 'test' => ['2', '3', '5']]);
669
        $docs[] = new Document(2, ['username' => 'john', 'test' => ['1', '3', '6']]);
670
        $docs[] = new Document(3, ['username' => 'rolf', 'test' => ['2', '3', '7']]);
671
        $index->addDocuments($docs);
672
        $index->refresh();
673
674
        $resultSet = $index->search('rolf');
675
        $this->assertEquals(1, $resultSet->count());
676
677
        $count = $index->count('rolf');
678
        $this->assertEquals(1, $count);
679
680
        // Test if source is returned
681
        $result = $resultSet->current();
682
        $this->assertEquals(3, $result->getId());
683
        $data = $result->getData();
684
        $this->assertEquals('rolf', $data['username']);
685
686
        $count = $index->count();
687
        $this->assertEquals(3, $count);
688
    }
689
690
    public function testSearchGet(): void
691
    {
692
        $index = $this->_createIndex();
693
        $docs = [];
694
        $docs[] = new Document(1, ['username' => 'hans']);
695
        $index->addDocuments($docs);
696
        $index->refresh();
697
698
        $resultSet = $index->search('hans', null, Request::GET);
699
        $this->assertEquals(1, $resultSet->count());
700
701
        $count = $index->count('hans', Request::GET);
702
        $this->assertEquals(1, $count);
703
    }
704
705
    public function testForcemerge(): void
706
    {
707
        $index = $this->_createIndex('testforcemerge_indextest', false, 3);
708
709
        $docs = [];
710
        $docs[] = new Document(1, ['foo' => 'bar']);
711
        $docs[] = new Document(2, ['foo' => 'bar']);
712
        $index->addDocuments($docs);
713
        $index->refresh();
714
715
        $stats = $index->getStats()->getData();
716
        $this->assertEquals(2, $stats['_all']['primaries']['docs']['count']);
717
        $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']);
718
719
        $index->deleteById('1');
720
        $index->refresh();
721
722
        $stats = $index->getStats()->getData();
723
        $this->assertEquals(1, $stats['_all']['primaries']['docs']['count']);
724
725
        $index->forcemerge(['max_num_segments' => 1]);
726
727
        $stats = $index->getStats()->getData();
728
        $this->assertEquals(1, $stats['_all']['primaries']['docs']['count']);
729
        $this->assertEquals(0, $stats['_all']['primaries']['docs']['deleted']);
730
    }
731
732
    public function testAnalyze(): void
733
    {
734
        $index = $this->_createIndex();
735
        $index->refresh();
736
        $returnedTokens = $index->analyze(['text' => 'foo']);
737
738
        $tokens = [
739
            [
740
                'token' => 'foo',
741
                'start_offset' => 0,
742
                'end_offset' => 3,
743
                'type' => '<ALPHANUM>',
744
                'position' => 0,
745
            ],
746
        ];
747
748
        $this->assertEquals($tokens, $returnedTokens);
749
    }
750
751
    public function testRequestEndpoint(): void
752
    {
753
        $index = $this->_createIndex();
754
        $index->refresh();
755
        $endpoint = new Analyze();
756
        $endpoint->setIndex('fooIndex');
757
        $endpoint->setBody(['text' => 'foo']);
758
        $returnedTokens = $index->requestEndpoint($endpoint)->getData()['tokens'];
759
760
        $tokens = [
761
            [
762
                'token' => 'foo',
763
                'start_offset' => 0,
764
                'end_offset' => 3,
765
                'type' => '<ALPHANUM>',
766
                'position' => 0,
767
            ],
768
        ];
769
770
        $this->assertEquals($tokens, $returnedTokens);
771
    }
772
773
    public function testAnalyzeExplain(): void
774
    {
775
        $index = $this->_createIndex();
776
        $index->refresh();
777
        $data = $index->analyze(['text' => 'foo', 'explain' => true], []);
778
779
        $this->assertArrayHasKey('custom_analyzer', $data);
780
    }
781
782
    public function testGetEmptyAliases(): void
783
    {
784
        $indexName = 'test-getaliases';
785
786
        $client = $this->_getClient();
787
        $index = $client->getIndex($indexName);
788
789
        $index->create([], [
790
            'recreate' => true,
791
        ]);
792
        $this->_waitForAllocation($index);
793
        $index->refresh();
794
        $index->forcemerge();
795
796
        $this->assertEquals([], $index->getAliases());
797
    }
798
}
799