forked from solariumphp/solarium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractTechproductsTestCase.php
5426 lines (4819 loc) · 222 KB
/
AbstractTechproductsTestCase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Solarium\Tests\Integration;
use PHPUnit\Framework\TestCase;
use Solarium\Component\ComponentAwareQueryInterface;
use Solarium\Component\Highlighting\Highlighting;
use Solarium\Component\QueryTraits\GroupingTrait;
use Solarium\Component\QueryTraits\TermsTrait;
use Solarium\Component\Result\Facet\Pivot\PivotItem;
use Solarium\Component\Result\Grouping\FieldGroup;
use Solarium\Component\Result\Grouping\QueryGroup;
use Solarium\Component\Result\Grouping\Result as GroupingResult;
use Solarium\Component\Result\Grouping\ValueGroup;
use Solarium\Component\Result\Terms\Result as TermsResult;
use Solarium\Core\Client\Adapter\ConnectionTimeoutAwareInterface;
use Solarium\Core\Client\Adapter\Curl;
use Solarium\Core\Client\Adapter\TimeoutAwareInterface;
use Solarium\Core\Client\ClientInterface;
use Solarium\Core\Client\Request;
use Solarium\Core\Client\Response;
use Solarium\Core\Event\Events;
use Solarium\Core\Query\AbstractDocument;
use Solarium\Core\Query\AbstractQuery;
use Solarium\Core\Query\Helper;
use Solarium\Core\Query\QueryInterface;
use Solarium\Core\Query\RequestBuilderInterface;
use Solarium\Exception\HttpException;
use Solarium\Exception\RuntimeException;
use Solarium\Exception\UnexpectedValueException;
use Solarium\Plugin\BufferedAdd\Event\AddDocument as BufferedAddAddDocumentEvent;
use Solarium\Plugin\BufferedAdd\Event\Events as BufferedAddEvents;
use Solarium\Plugin\BufferedAdd\Event\PostCommit as BufferedAddPostCommitEvent;
use Solarium\Plugin\BufferedAdd\Event\PostFlush as BufferedAddPostFlushEvent;
use Solarium\Plugin\BufferedAdd\Event\PreCommit as BufferedAddPreCommitEvent;
use Solarium\Plugin\BufferedAdd\Event\PreFlush as BufferedAddPreFlushEvent;
use Solarium\Plugin\BufferedDelete\Event\AddDeleteById as BufferedDeleteAddDeleteByIdEvent;
use Solarium\Plugin\BufferedDelete\Event\AddDeleteQuery as BufferedDeleteAddDeleteQueryEvent;
use Solarium\Plugin\BufferedDelete\Event\Events as BufferedDeleteEvents;
use Solarium\Plugin\Loadbalancer\Event\EndpointFailure as LoadbalancerEndpointFailureEvent;
use Solarium\Plugin\Loadbalancer\Event\Events as LoadbalancerEvents;
use Solarium\Plugin\Loadbalancer\Loadbalancer;
use Solarium\Plugin\ParallelExecution\ParallelExecution;
use Solarium\Plugin\PrefetchIterator;
use Solarium\QueryType\Luke\Query as LukeQuery;
use Solarium\QueryType\Luke\Result\Doc\DocFieldInfo as LukeDocFieldInfo;
use Solarium\QueryType\Luke\Result\Doc\DocInfo as LukeDocInfo;
use Solarium\QueryType\Luke\Result\Fields\FieldInfo as LukeFieldInfo;
use Solarium\QueryType\Luke\Result\Index\Index as LukeIndexResult;
use Solarium\QueryType\Luke\Result\Schema\Schema as LukeSchemaResult;
use Solarium\QueryType\ManagedResources\Query\AbstractQuery as AbstractManagedResourcesQuery;
use Solarium\QueryType\ManagedResources\Query\Stopwords as StopwordsQuery;
use Solarium\QueryType\ManagedResources\Query\Synonyms as SynonymsQuery;
use Solarium\QueryType\ManagedResources\Query\Synonyms\Synonyms;
use Solarium\QueryType\ManagedResources\RequestBuilder\Resource as ResourceRequestBuilder;
use Solarium\QueryType\ManagedResources\Result\Resources\Resource as ResourceResultItem;
use Solarium\QueryType\ManagedResources\Result\Synonyms\Synonyms as SynonymsResultItem;
use Solarium\QueryType\Select\Query\Query as SelectQuery;
use Solarium\QueryType\Select\Result\Document;
use Solarium\QueryType\Select\Result\Result as SelectResult;
use Solarium\QueryType\Update\Query\Query as UpdateQuery;
use Solarium\QueryType\Update\RequestBuilder\Xml as XmlUpdateRequestBuilder;
use Solarium\Support\Utility;
use Solarium\Tests\Integration\Plugin\EventTimer;
use Symfony\Contracts\EventDispatcher\Event;
use TRegx\PhpUnit\DataProviders\DataProvider;
abstract class AbstractTechproductsTestCase extends TestCase
{
/**
* @var ClientInterface
*/
protected static $client;
/**
* @var string
*/
protected static $name;
/**
* @var array
*/
protected static $config;
/**
* Major Solr version.
*
* @var int
*/
protected static $solrVersion;
/**
* Solr running on Windows?
*
* SOLR-15895 has to be avoided when testing against Solr on Windows.
*
* @var bool
*/
protected static $isSolrOnWindows;
/**
* Asserts that a document contains exactly the expected fields.
*
* {@internal We used to compare the actual array of fields directly to the
* expected array with {@see assertSame()} but that stopped working
* with Solr 9.7.0 because the order in which fields are returned
* has changed for some queries. There was never a guarantee that
* Solr maintains field order (SOLR-1190), we had just been lucky
* that it had always happened to work out before.}
*/
public static function assertDocumentHasFields(array $expectedFields, AbstractDocument $actualDocument, string $message = ''): void
{
$actualFields = $actualDocument->getFields();
Utility::recursiveKeySort($actualFields);
Utility::recursiveKeySort($expectedFields);
static::assertSame($expectedFields, $actualFields, $message);
}
abstract protected static function createTechproducts(): void;
public static function setUpBeforeClass(): void
{
self::$name = uniqid();
static::createTechproducts();
$ping = self::$client->createPing();
self::$client->ping($ping);
$query = self::$client->createApi([
'version' => Request::API_V1,
'handler' => 'admin/info/system',
]);
$response = self::$client->execute($query);
$system = $response->getData();
$solrSpecVersion = $system['lucene']['solr-spec-version'];
self::$solrVersion = (int) strstr($solrSpecVersion, '.', true);
$systemName = $system['system']['name'];
self::$isSolrOnWindows = str_starts_with($systemName, 'Windows');
// disable automatic commits for update tests
$query = self::$client->createApi([
'version' => Request::API_V1,
'handler' => self::$name.'/config',
'method' => Request::METHOD_POST,
'rawdata' => json_encode([
'set-property' => [
'updateHandler.autoCommit.maxDocs' => -1,
'updateHandler.autoCommit.maxTime' => -1,
'updateHandler.autoCommit.openSearcher' => true,
'updateHandler.autoSoftCommit.maxDocs' => -1,
'updateHandler.autoSoftCommit.maxTime' => -1,
],
]),
]);
self::$client->execute($query);
// ensure correct config for update tests
$query = self::$client->createApi([
'version' => Request::API_V1,
'handler' => self::$name.'/config/updateHandler',
]);
$response = self::$client->execute($query);
$config = $response->getData()['config'];
static::assertEquals([
'maxDocs' => -1,
'maxTime' => -1,
'openSearcher' => true,
], $config['updateHandler']['autoCommit']);
static::assertEquals([
'maxDocs' => -1,
'maxTime' => -1,
], $config['updateHandler']['autoSoftCommit']);
try {
// index techproducts sample data
$dataDir = __DIR__.
DIRECTORY_SEPARATOR.'..'.
DIRECTORY_SEPARATOR.'..'.
DIRECTORY_SEPARATOR.'lucene-solr'.
DIRECTORY_SEPARATOR.'solr'.
DIRECTORY_SEPARATOR.'example'.
DIRECTORY_SEPARATOR.'exampledocs';
foreach (glob($dataDir.DIRECTORY_SEPARATOR.'*.xml') as $file) {
$update = self::$client->createUpdate();
$update->setRequestFormat(UpdateQuery::REQUEST_FORMAT_XML);
if (null !== $encoding = Utility::getXmlEncoding($file)) {
$update->setInputEncoding($encoding);
}
$update->addRawXmlFile($file);
self::$client->update($update);
}
// UTF8TEST was removed for Solr 9.8 in SOLR-17556
if (9 <= self::$solrVersion) {
$update = self::$client->createUpdate();
$utf8test = $update->createDocument();
$utf8test->setField('id', 'UTF8TEST');
$utf8test->setField('manu', 'Apache Software Foundation');
$utf8test->setField('cat', 'software');
$utf8test->setField('cat', 'search');
$utf8test->setField('features', 'êâîôû');
$utf8test->setField('price', 0.0);
$utf8test->setField('inStock', true);
$update->addDocument($utf8test);
self::$client->update($update);
}
$update = self::$client->createUpdate();
$update->addCommit(true, true);
self::$client->update($update);
// check that everything was indexed properly
$select = self::$client->createSelect();
$select->setFields('id');
$result = self::$client->select($select);
static::assertSame(32, $result->getNumFound());
$select->setQuery('êâîôû');
$result = self::$client->select($select);
static::assertCount(1, $result);
static::assertDocumentHasFields([
'id' => 'UTF8TEST',
], $result->getIterator()->current());
$select->setQuery('这是一个功能');
$result = self::$client->select($select);
static::assertCount(1, $result);
static::assertDocumentHasFields([
'id' => 'GB18030TEST',
], $result->getIterator()->current());
} catch (\Exception $e) {
self::tearDownAfterClass();
static::markTestSkipped('Solr techproducts sample data not indexed properly.');
}
}
/**
* This data provider can be used to test functional equivalence in parsing results
* from the same queries with different response writers.
*/
public function responseWriterProvider(): array
{
return [
[AbstractQuery::WT_JSON],
[AbstractQuery::WT_PHPS],
];
}
/**
* This data provider should be used by all UpdateQuery tests that don't test request
* format specific Commands to ensure functional equivalence between the formats.
*/
public function updateRequestFormatProvider(): array
{
return [
[UpdateQuery::REQUEST_FORMAT_XML],
[UpdateQuery::REQUEST_FORMAT_JSON],
];
}
/**
* This data provider crosses {@see updateRequestFormatProvider()} with
* {@see responseWriterProvider()}.
*/
public function crossRequestFormatResponseWriterProvider(): DataProvider
{
return DataProvider::cross(
$this->updateRequestFormatProvider(),
$this->responseWriterProvider(),
);
}
/**
* @dataProvider responseWriterProvider
*/
public function testPing(string $responseWriter)
{
$ping = self::$client->createPing();
$ping->setResponseWriter($responseWriter);
$result = self::$client->ping($ping);
$this->assertSame(0, $result->getStatus());
$this->assertSame('OK', $result->getPingStatus());
if ($this instanceof AbstractCloudTestCase) {
$this->assertTrue($result->getZkConnected());
} else {
$this->assertNull($result->getZkConnected());
}
}
/**
* @dataProvider responseWriterProvider
*/
public function testSelect(string $responseWriter)
{
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$select->setSorts(['id' => SelectQuery::SORT_ASC]);
$result = self::$client->select($select);
$this->assertSame(32, $result->getNumFound());
$this->assertCount(10, $result);
$ids = [];
/** @var Document $document */
foreach ($result as $document) {
$ids[] = $document->id;
}
$this->assertEquals([
'0579B002',
'100-435805',
'3007WFP',
'6H500F0',
'9885A004',
'EN7800GTX/2DHTV/256M',
'EUR',
'F8V7067-APL-KIT',
'GB18030TEST',
'GBP',
], $ids);
}
public function testJsonSerializeSelectResult()
{
$select = self::$client->createSelect();
$select->setResponseWriter(AbstractQuery::WT_JSON);
$result = self::$client->select($select);
$expectedJson = $result->getResponse()->getBody();
// this only calls SelectResult::jsonSerialize() which gets the document data from the parsed response
$json = json_encode($result);
$this->assertJsonStringEqualsJsonString($expectedJson, $json);
// this calls Document::jsonSerialize() on every document instead
$documents = json_encode($result->getDocuments());
$this->assertStringContainsString($documents, $json);
}
/**
* @see https://solr.apache.org/guide/the-standard-query-parser.html#escaping-special-characters
*
* @dataProvider crossRequestFormatResponseWriterProvider
*/
public function testEscapes(string $requestFormat, string $responseWriter)
{
$escapeChars = [' ', '+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '/', '\\'];
$cat = [implode('', $escapeChars)];
foreach ($escapeChars as $char) {
$cat[] = 'a'.$char.'b';
}
$update = self::$client->createUpdate();
$update->setRequestFormat($requestFormat);
$update->setResponseWriter($responseWriter);
$doc = $update->createDocument();
$doc->setField('id', 'solarium-test-escapes');
$doc->setField('name', 'Solarium Test Escapes');
$doc->setField('cat', $cat);
$update->addDocument($doc);
$update->addCommit(true, true);
self::$client->update($update);
// check if stored correctly in index
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$select->setQuery('id:%T1%', ['solarium-test-escapes']);
$result = self::$client->select($select);
$this->assertCount(1, $result);
$this->assertSame($cat, $result->getIterator()->current()->getFields()['cat']);
foreach ($escapeChars as $char) {
// as term
$select->setQuery('cat:%T1%', ['a'.$char.'b']);
$result = self::$client->select($select);
$this->assertCount(1, $result, $msg = sprintf('Failure with term containing \'%s\'.', $char));
$this->assertSame('solarium-test-escapes', $result->getIterator()->current()->getFields()['id'], $msg);
// as phrase
$select->setQuery('cat:%P1%', ['a'.$char.'b']);
$result = self::$client->select($select);
$this->assertCount(1, $result, $msg = sprintf('Failure with phrase containing \'%s\'.', $char));
$this->assertSame('solarium-test-escapes', $result->getIterator()->current()->getFields()['id'], $msg);
}
// cleanup
$update->addDeleteQuery('cat:%T1%', [$cat[0]]);
$update->addCommit(true, true);
self::$client->update($update);
$select->setQuery('id:solarium-test-escapes');
$result = self::$client->select($select);
$this->assertCount(0, $result);
}
/**
* @see https://github.com/solariumphp/solarium/issues/1104
*
* @dataProvider crossRequestFormatResponseWriterProvider
*/
public function testPhraseQuery(string $requestFormat, string $responseWriter)
{
$phrase = "^The 17\" O'Conner && O`Series \n OR a || 1%2 1~2 1*2 \r\n book? \r \twhat \\ text: }{ )( ][ - + // \n\r ok? end$";
$update = self::$client->createUpdate();
$update->setResponseWriter($responseWriter);
$update->setRequestFormat($requestFormat);
$doc = $update->createDocument();
$doc->setField('id', 'solarium-test-phrase');
$doc->setField('name', 'Solarium Test Phrase Query');
$doc->setField('cat', [$phrase]);
$update->addDocument($doc);
$update->addCommit(true, true);
self::$client->update($update);
if ($update::REQUEST_FORMAT_XML === $requestFormat) {
/*
* Per https://www.w3.org/TR/REC-xml/#sec-line-ends line breaks are normalized
*
* [...] by translating both the two-character sequence #xD #xA and
* any #xD that is not followed by #xA to a single #xA character.
*/
$phrase = str_replace(["\r\n", "\r"], ["\n", "\n"], $phrase);
}
// check if stored correctly in index
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$select->setQuery('id:solarium-test-phrase');
$result = self::$client->select($select);
$this->assertSame([$phrase], $result->getIterator()->current()->getFields()['cat']);
// as term
$select->setQuery('cat:%T1%', [$phrase]);
$result = self::$client->select($select);
$this->assertCount(1, $result);
$this->assertSame('solarium-test-phrase', $result->getIterator()->current()->getFields()['id']);
// as phrase
$select->setQuery('cat:%P1%', [$phrase]);
$result = self::$client->select($select);
$this->assertCount(1, $result);
$this->assertSame('solarium-test-phrase', $result->getIterator()->current()->getFields()['id']);
// cleanup
$update->addDeleteQuery('cat:%P1%', [$phrase]);
$update->addCommit(true, true);
self::$client->update($update);
$select->setQuery('id:solarium-test-phrase');
$result = self::$client->select($select);
$this->assertCount(0, $result);
}
/**
* @see https://github.com/solariumphp/solarium/issues/974
* @see https://solr.apache.org/guide/local-parameters-in-queries.html#basic-syntax-of-local-parameters
*
* @dataProvider crossRequestFormatResponseWriterProvider
*/
public function testLocalParamValueEscapes(string $requestFormat, string $responseWriter)
{
$categories = [
'solarium-test-localparamvalue-escapes',
'space: the final frontier',
"'single-quote",
'"double-quote',
'escaped backslash \\',
'right-curly-bracket}',
// \ in and of itself and {! don't need escaping
'unescaped-backslash-\\',
'{!left-curly-bracket',
];
$update = self::$client->createUpdate();
$update->setResponseWriter($responseWriter);
$update->setRequestFormat($requestFormat);
$doc = $update->createDocument();
$doc->setField('id', 'solarium-test-localparamvalue-escapes');
$doc->setField('name', 'Solarium Test Local Param Value Escapes');
$doc->setField('cat', $categories);
$update->addDocument($doc);
$update->addCommit(true, true);
self::$client->update($update);
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$select->setRows(0);
$facetSet = $select->getFacetSet();
// without escaping, ' " } cause an error
foreach ($categories as $cat) {
$facetSet->createFacetField($cat)->setField('cat')->setContains($cat);
}
// without escaping, 'electronics and computer' would match 3 values that contain 'electronics' in techproducts
$facetSet->createFacetField('electronics')->setField('cat')->setContains('electronics and computer');
// without escaping, a space can be abused for Local Parameter Injection
$facetSet->createFacetField('ELECTRONICS')->setField('cat')->setContains('ELECTRONICS')->setContainsIgnoreCase(true);
$facetSet->createFacetField('ELECTRONICS_LPI')->setField('cat')->setContains('ELECTRONICS facet.contains.ignoreCase=true');
$result = self::$client->select($select);
foreach ($categories as $cat) {
$facet = $result->getFacetSet()->getFacet($cat);
$this->assertEquals([$cat => 1], $facet->getValues());
}
$facet = $result->getFacetSet()->getFacet('electronics');
$this->assertEquals(['electronics and computer1' => 1], $facet->getValues());
$facet = $result->getFacetSet()->getFacet('ELECTRONICS');
$this->assertCount(3, $facet);
$facet = $result->getFacetSet()->getFacet('ELECTRONICS_LPI');
$this->assertCount(0, $facet);
// cleanup
$update->addDeleteById('solarium-test-localparamvalue-escapes');
$update->addCommit(true, true);
self::$client->update($update);
$select->setQuery('id:solarium-test-localparamvalue-escapes');
$result = self::$client->select($select);
$this->assertCount(0, $result);
}
/**
* @dataProvider responseWriterProvider
*/
public function testRangeQueries(string $responseWriter)
{
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$select->setQuery(
$select->getHelper()->rangeQuery('price', null, 80)
);
$result = self::$client->select($select);
$this->assertSame(6, $result->getNumFound());
$this->assertCount(6, $result);
// VS1GB400C3 costs 74.99 and is the only product in the range between 70.23 and 80.00.
$select->setQuery(
$select->getHelper()->rangeQuery('price', 70.23, 80)
);
$result = self::$client->select($select);
$this->assertSame(1, $result->getNumFound());
$this->assertCount(1, $result);
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, null)
);
$result = self::$client->select($select);
$this->assertSame(11, $result->getNumFound());
$this->assertCount(10, $result);
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, null, false)
);
$result = self::$client->select($select);
$this->assertSame(10, $result->getNumFound());
$this->assertCount(10, $result);
$select->setQuery(
$select->getHelper()->rangeQuery('store', '-90,-90', '90,90')
);
$result = self::$client->select($select);
$this->assertSame(2, $result->getNumFound());
$this->assertCount(2, $result);
$select->setQuery(
$select->getHelper()->rangeQuery('store', '-90,-180', '90,180')
);
$result = self::$client->select($select);
$this->assertSame(14, $result->getNumFound());
$this->assertCount(10, $result);
// MA147LL/A was manufactured on 2005-10-12T08:00:00Z, F8V7067-APL-KIT on 2005-08-01T16:30:25Z
$select->setFields('id,manufacturedate_dt');
$select->addSort('manufacturedate_dt', $select::SORT_DESC);
$select->setQuery(
$select->getHelper()->rangeQuery('manufacturedate_dt', '2005-01-01T00:00:00Z', '2005-12-31T23:59:59Z')
);
$result = self::$client->select($select);
$this->assertSame(2, $result->getNumFound());
$iterator = $result->getIterator();
$this->assertDocumentHasFields([
'id' => 'MA147LL/A',
'manufacturedate_dt' => '2005-10-12T08:00:00Z',
], $iterator->current());
$iterator->next();
$this->assertDocumentHasFields([
'id' => 'F8V7067-APL-KIT',
'manufacturedate_dt' => '2005-08-01T16:30:25Z',
], $iterator->current());
// VS1GB400C3 costs 74.99, SP2514N costs 92.0, 0579B002 costs 179.99
$select->setFields('id,price');
$select->clearSorts()->addSort('price', $select::SORT_ASC);
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, 179.99, [true, true])
);
$result = self::$client->select($select);
$this->assertSame(3, $result->getNumFound());
$iterator = $result->getIterator();
$this->assertDocumentHasFields([
'id' => 'VS1GB400C3',
'price' => 74.99,
], $iterator->current());
$iterator->next();
$this->assertDocumentHasFields([
'id' => 'SP2514N',
'price' => 92.0,
], $iterator->current());
$iterator->next();
$this->assertDocumentHasFields([
'id' => '0579B002',
'price' => 179.99,
], $iterator->current());
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, 179.99, [true, false])
);
$result = self::$client->select($select);
$this->assertSame(2, $result->getNumFound());
$iterator = $result->getIterator();
$this->assertDocumentHasFields([
'id' => 'VS1GB400C3',
'price' => 74.99,
], $iterator->current());
$iterator->next();
$this->assertDocumentHasFields([
'id' => 'SP2514N',
'price' => 92.0,
], $iterator->current());
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, 179.99, [false, true])
);
$result = self::$client->select($select);
$this->assertSame(2, $result->getNumFound());
$iterator = $result->getIterator();
$this->assertDocumentHasFields([
'id' => 'SP2514N',
'price' => 92.0,
], $iterator->current());
$iterator->next();
$this->assertDocumentHasFields([
'id' => '0579B002',
'price' => 179.99,
], $iterator->current());
$select->setQuery(
$select->getHelper()->rangeQuery('price', 74.99, 179.99, [false, false])
);
$result = self::$client->select($select);
$this->assertSame(1, $result->getNumFound());
$iterator = $result->getIterator();
$this->assertDocumentHasFields([
'id' => 'SP2514N',
'price' => 92.0,
], $iterator->current());
}
public function testFacetHighlightSpellcheckComponent()
{
$select = self::$client->createSelect();
// In the techproducts example, the request handler "select" doesn't neither contain a spellcheck component nor
// a highlighter or facets. But the self-defined "componentdemo" request handler does.
$select->setHandler('componentdemo');
// Search for misspelled "power cort".
$select->setQuery('power cort');
$spellcheck = $select->getSpellcheck();
// Some spellcheck dictionaries need to be built first, but not on every request!
$spellcheck->setBuild(true);
$spellcheck->setCount(5);
$spellcheck->setAlternativeTermCount(2);
// Order of suggestions is wrong on SolrCloud with spellcheck.extendedResults=false (SOLR-9060)
$spellcheck->setExtendedResults(true);
$spellcheck->setCollate(true);
$spellcheck->setCollateExtendedResults(true);
$spellcheck->setMaxCollationTries(5);
$spellcheck->setMaxCollations(3);
$result = self::$client->select($select);
$this->assertSame(0, $result->getNumFound());
$this->assertFalse($result->getSpellcheck()->getCorrectlySpelled());
$this->assertSame(
[
'power' => 'power',
'cort' => 'cord',
],
$result->getSpellcheck()->getCollations()[0]->getCorrections()
);
$words = [];
foreach ($result->getSpellcheck()->getSuggestions()[0]->getWords() as $suggestion) {
$words[] = $suggestion['word'];
}
$this->assertEquals([
'corp',
'cord',
'card',
], $words);
$spellcheck->setDictionary(['default', 'wordbreak']);
$result = self::$client->select($select);
$this->assertSame(0, $result->getNumFound());
$this->assertFalse($result->getSpellcheck()->getCorrectlySpelled());
$this->assertSame(
[
'power' => 'power',
'cort' => 'cord',
],
$result->getSpellcheck()->getCollations()[0]->getCorrections()
);
$select->setQuery('power cord');
$highlighting = $select->getHighlighting();
$highlighting->setMethod(Highlighting::METHOD_ORIGINAL);
$highlighting->setSimplePrefix('<b>')->setSimplePostfix('</b>');
$facetSet = $select->getFacetSet();
$facetSet->createFacetField('stock')->setField('inStock');
$result = self::$client->select($select);
$this->assertSame(1, $result->getNumFound());
foreach ($result as $document) {
$this->assertSame('F8V7067-APL-KIT', $document->id);
}
$this->assertSame(
['car <b>power</b> adapter, white'],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getField('features')
);
$this->assertSame(
['Belkin Mobile <b>Power</b> <b>Cord</b> for iPod w/ Dock'],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getField('name')
);
$this->assertSame(
[
'features' => ['car <b>power</b> adapter, white'],
'name' => ['Belkin Mobile <b>Power</b> <b>Cord</b> for iPod w/ Dock'],
],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getFields()
);
foreach ($result->getFacetSet() as $facetFieldName => $facetField) {
$this->assertSame('stock', $facetFieldName);
// The power cord is not in stock! In the techproducts example that is reflected by the string 'false'.
$this->assertSame(1, $facetField->getValues()['false']);
}
}
/**
* @see https://solr.apache.org/guide/solr/latest/query-guide/faceting.html#combining-stats-component-with-pivots
*
* @dataProvider responseWriterProvider
*/
public function testFacetPivotsWithStatsComponent(string $responseWriter)
{
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
$facetSet = $select->getFacetSet();
$facet = $facetSet->createFacetPivot('piv1');
$facet->addFields('{!stats=piv1}cat');
$stats = $select->getStats();
$stats->createField('{!tag=piv1 sum=true percentiles="1,10,90,99"}price');
$stats->createField('{!tag=piv1 min=true max=true mean=true}popularity');
$result = self::$client->select($select);
/** @var PivotItem $pivotItem */
$pivotItem = $result->getFacetSet()->getFacet('piv1')->getPivot()[0];
$pivotStats = $pivotItem->getStats();
$this->assertCount(2, $pivotStats->getResults());
$result1 = $pivotStats->getResult('price');
$this->assertSame('price', $result1->getName());
$this->assertIsFloat($result1->getSum());
$this->assertSame(['1.0', '10.0', '90.0', '99.0'], array_keys($result1->getPercentiles()));
$result2 = $pivotStats->getResult('popularity');
$this->assertSame('popularity', $result2->getName());
$this->assertSame(0.0, $result2->getMin());
$this->assertSame(10.0, $result2->getMax());
$this->assertSame(5.25, $result2->getMean());
}
/**
* @dataProvider crossHighlightingMethodResponseWriterProvider
*/
public function testHighlightingComponentMethods(string $method, string $responseWriter)
{
$select = self::$client->createSelect();
$select->setResponseWriter($responseWriter);
// The self-defined "componentdemo" request handler has a highlighting component.
$select->setHandler('componentdemo');
$select->setQuery('id:F8V7067-APL-KIT');
$highlighting = $select->getHighlighting();
$highlighting->setMethod($method);
$highlighting->setFields('name, features');
$highlighting->getField('features')->setSimplePrefix('<u class="hl">')->setSimplePostfix('</u>');
$highlighting->setQuery('(power cord) OR (power adapter)');
$highlighting->setQueryParser('edismax');
$highlighting->setSimplePrefix('<b>')->setSimplePostfix('</b>');
// We don't set HTML encoding for ease of comparison, this can open an XSS attack vector.
// Make sure that you set it by default in solrconfig.xml or on every request if required!
// $highlighting->setEncoder(Highlighting::ENCODER_HTML);
$result = self::$client->select($select);
$this->assertSame(1, $result->getNumFound());
foreach ($result as $document) {
$this->assertSame('F8V7067-APL-KIT', $document->id);
}
$this->assertSame(
['Belkin Mobile <b>Power</b> <b>Cord</b> for iPod w/ Dock'],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getField('name')
);
$this->assertSame(
['car <u class="hl">power</u> <u class="hl">adapter</u>, white'],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getField('features')
);
$this->assertSame(
[
'name' => ['Belkin Mobile <b>Power</b> <b>Cord</b> for iPod w/ Dock'],
'features' => ['car <u class="hl">power</u> <u class="hl">adapter</u>, white'],
],
$result->getHighlighting()->getResult('F8V7067-APL-KIT')->getFields()
);
}
public function crossHighlightingMethodResponseWriterProvider(): DataProvider
{
$highlightingMethods = [
[Highlighting::METHOD_UNIFIED],
[Highlighting::METHOD_ORIGINAL],
[Highlighting::METHOD_FASTVECTOR],
];
return DataProvider::cross(
$highlightingMethods,
$this->responseWriterProvider(),
);
}
/**
* @see https://github.com/solariumphp/solarium/issues/184
*/
public function testSpellCheckComponentWithSameWordMisspelledMultipleTimes()
{
$select = self::$client->createSelect();
$select->setHandler('spell');
$select->getEDisMax()->setMinimumMatch('100%');
$select->setQuery('power cort cort');
$spellcheck = $select->getSpellcheck();
// Some spellcheck dictionaries need to be built first, but not on every request!
$spellcheck->setBuild(true);
// Order of suggestions is wrong on SolrCloud with spellcheck.extendedResults=false (SOLR-9060)
$spellcheck->setExtendedResults(true);
$result = self::$client->select($select);
$this->assertSame(0, $result->getNumFound());
$this->assertFalse($result->getSpellcheck()->getCorrectlySpelled());
$this->assertSame(
[
'power' => 'power',
'cort' => [
'cord',
'cord',
],
],
$result->getSpellcheck()->getCollations()[0]->getCorrections()
);
$words = [];
foreach ($result->getSpellcheck()->getSuggestions()[0]->getWords() as $suggestion) {
$words[] = $suggestion['word'];
}
$this->assertEquals([
'corp',
'cord',
'card',
], $words);
$spellcheck->setDictionary(['default', 'wordbreak']);
$result = self::$client->select($select);
$this->assertSame(0, $result->getNumFound());
$this->assertFalse($result->getSpellcheck()->getCorrectlySpelled());
$this->assertSame(
[
'power' => 'power',
'cort' => [
'cord',
'cord',
],
],
$result->getSpellcheck()->getCollations()[0]->getCorrections()
);
}
/**
* The Grouping feature only works if groups are in the same shard. You must use the custom sharding feature to use the Grouping feature.
*
* @see https://cwiki.apache.org/confluence/display/solr/SolrCloud%20/#SolrCloud-KnownLimitations
*
* @dataProvider responseWriterProvider
*
* @group skip_for_solr_cloud
*/
public function testGroupingComponent(string $responseWriter)
{
self::$client->registerQueryType('grouping', GroupingTestQuery::class);
/** @var GroupingTestQuery $select */
$select = self::$client->createQuery('grouping');
$select->setResponseWriter($responseWriter);
$select->setQuery('solr memory');
$select->setFields('id');
$select->addSort('manu_exact', SelectQuery::SORT_ASC);
$grouping = $select->getGrouping();
$grouping->setFields('manu_exact');
$grouping->setSort('price asc');
$result = self::$client->select($select);
/** @var GroupingResult $groupingComponentResult */
$groupingComponentResult = $result->getComponent(ComponentAwareQueryInterface::COMPONENT_GROUPING);
/** @var FieldGroup $fieldGroup */
$fieldGroup = $groupingComponentResult->getGroup('manu_exact');
$this->assertSame(6, $fieldGroup->getMatches());
$this->assertCount(5, $fieldGroup);
$groupIterator = $fieldGroup->getIterator();
/** @var ValueGroup $valueGroup */
$valueGroup = $groupIterator->current();
$this->assertSame(1, $valueGroup->getNumFound());
$this->assertSame(0, $valueGroup->getStart());
$this->assertSame('A-DATA Technology Inc.', $valueGroup->getValue());
$docIterator = $valueGroup->getIterator();
/** @var Document $doc */
$doc = $docIterator->current();
$this->assertSame('VDBDB1A16', $doc->getFields()['id']);
$groupIterator->next();
$valueGroup = $groupIterator->current();
$this->assertSame(1, $valueGroup->getNumFound());
$this->assertSame(0, $valueGroup->getStart());
$this->assertSame('ASUS Computer Inc.', $valueGroup->getValue());
$docIterator = $valueGroup->getIterator();
$doc = $docIterator->current();
$this->assertSame('EN7800GTX/2DHTV/256M', $doc->getFields()['id']);
$groupIterator->next();
$valueGroup = $groupIterator->current();
$this->assertSame(1, $valueGroup->getNumFound());
$this->assertSame(0, $valueGroup->getStart());
$this->assertSame('Apache Software Foundation', $valueGroup->getValue());
$docIterator = $valueGroup->getIterator();
$doc = $docIterator->current();
$this->assertSame('SOLR1000', $doc->getFields()['id']);
$groupIterator->next();
$valueGroup = $groupIterator->current();
$this->assertSame(1, $valueGroup->getNumFound());
$this->assertSame(0, $valueGroup->getStart());
$this->assertSame('Canon Inc.', $valueGroup->getValue());
$docIterator = $valueGroup->getIterator();
$doc = $docIterator->current();
$this->assertSame('0579B002', $doc->getFields()['id']);
$groupIterator->next();
$valueGroup = $groupIterator->current();
$this->assertSame(2, $valueGroup->getNumFound());
$this->assertSame(0, $valueGroup->getStart());
$this->assertSame('Corsair Microsystems Inc.', $valueGroup->getValue());
$docIterator = $valueGroup->getIterator();