Repository navigation
Expand file tree
/
Copy pathSphinxClient.java
More file actions
1539 lines (1326 loc) · 44.9 KB
/
Copy pathSphinxClient.java
File metadata and controls
1539 lines (1326 loc) · 44.9 KB
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
/*
* $Id$
*
* Java version of Sphinx searchd client (Java API)
*
* Copyright (c) 2007, Vladimir Fedorkov
* Copyright (c) 2007-2016, Andrew Aksyonoff
* Copyright (c) 2008-2016, Sphinx Technologies Inc
* All rights reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License. You should
* have received a copy of the LGPL license along with this program; if you
* did not, you can find it at http://www.gnu.org/
*
* WARNING!!!
*
* As of 2015, we strongly recommend to use either SphinxQL or REST APIs
* rather than the native SphinxAPI.
*
* While both the native SphinxAPI protocol and the existing APIs will
* continue to exist, and perhaps should not even break (too much), exposing
* all the new features via multiple different native API implementations
* is too much of a support complication for us.
*
* That said, you're welcome to overtake the maintenance of any given
* official API, and remove this warning ;)
*
*/
package org.sphx.api;
import java.io.*;
import java.net.*;
import java.util.*;
import java.net.SocketAddress.*;
/** Sphinx client class */
public class SphinxClient
{
/* matching modes */
public final static int SPH_MATCH_ALL = 0;
public final static int SPH_MATCH_ANY = 1;
public final static int SPH_MATCH_PHRASE = 2;
public final static int SPH_MATCH_BOOLEAN = 3;
public final static int SPH_MATCH_EXTENDED = 4;
public final static int SPH_MATCH_FULLSCAN = 5;
public final static int SPH_MATCH_EXTENDED2 = 6;
/* ranking modes (extended2 only) */
public final static int SPH_RANK_PROXIMITY_BM25 = 0;
public final static int SPH_RANK_BM25 = 1;
public final static int SPH_RANK_NONE = 2;
public final static int SPH_RANK_WORDCOUNT = 3;
public final static int SPH_RANK_PROXIMITY = 4;
public final static int SPH_RANK_MATCHANY = 5;
public final static int SPH_RANK_FIELDMASK = 6;
public final static int SPH_RANK_SPH04 = 7;
public final static int SPH_RANK_EXPR = 8;
public final static int SPH_RANK_TOTAL = 9;
/* sorting modes */
public final static int SPH_SORT_RELEVANCE = 0;
public final static int SPH_SORT_ATTR_DESC = 1;
public final static int SPH_SORT_ATTR_ASC = 2;
public final static int SPH_SORT_TIME_SEGMENTS = 3;
public final static int SPH_SORT_EXTENDED = 4;
public final static int SPH_SORT_EXPR = 5;
/* grouping functions */
public final static int SPH_GROUPBY_DAY = 0;
public final static int SPH_GROUPBY_WEEK = 1;
public final static int SPH_GROUPBY_MONTH = 2;
public final static int SPH_GROUPBY_YEAR = 3;
public final static int SPH_GROUPBY_ATTR = 4;
public final static int SPH_GROUPBY_ATTRPAIR = 5;
/* searchd reply status codes */
public final static int SEARCHD_OK = 0;
public final static int SEARCHD_ERROR = 1;
public final static int SEARCHD_RETRY = 2;
public final static int SEARCHD_WARNING = 3;
/* attribute types */
public final static int SPH_ATTR_INTEGER = 1;
public final static int SPH_ATTR_TIMESTAMP = 2;
public final static int SPH_ATTR_ORDINAL = 3;
public final static int SPH_ATTR_BOOL = 4;
public final static int SPH_ATTR_FLOAT = 5;
public final static int SPH_ATTR_BIGINT = 6;
public final static int SPH_ATTR_STRING = 7;
public final static int SPH_ATTR_MULTI = 0x40000001;
public final static int SPH_ATTR_MULTI64 = 0x40000002;
/* searchd commands */
private final static int SEARCHD_COMMAND_SEARCH = 0;
private final static int SEARCHD_COMMAND_EXCERPT = 1;
private final static int SEARCHD_COMMAND_UPDATE = 2;
private final static int SEARCHD_COMMAND_KEYWORDS = 3;
private final static int SEARCHD_COMMAND_PERSIST = 4;
private final static int SEARCHD_COMMAND_FLUSHATTRS = 7;
/* searchd command versions */
private final static int VER_MAJOR_PROTO = 0x1;
private final static int VER_COMMAND_SEARCH = 0x119;
private final static int VER_COMMAND_EXCERPT = 0x102;
private final static int VER_COMMAND_UPDATE = 0x103;
private final static int VER_COMMAND_KEYWORDS = 0x100;
private final static int VER_COMMAND_FLUSHATTRS = 0x100;
/* filter types */
private final static int SPH_FILTER_VALUES = 0;
private final static int SPH_FILTER_RANGE = 1;
private final static int SPH_FILTER_FLOATRANGE = 2;
private String _host;
private int _port;
private String _path;
private Socket _socket;
private int _offset;
private int _limit;
private int _mode;
private int[] _weights;
private int _sort;
private String _sortby;
private int _minId;
private int _maxId;
private ByteArrayOutputStream _rawFilters;
private DataOutputStream _filters;
private int _filterCount;
private String _groupBy;
private int _groupFunc;
private String _groupSort;
private String _groupDistinct;
private int _maxMatches;
private int _cutoff;
private int _retrycount;
private int _retrydelay;
private String _latitudeAttr;
private String _longitudeAttr;
private float _latitude;
private float _longitude;
private String _error;
private String _warning;
private boolean _connerror;
private int _timeout;
private ArrayList _reqs;
private Map _indexWeights;
private int _ranker;
private String _rankexpr;
private int _maxQueryTime;
private Map _fieldWeights;
private Map _overrideTypes;
private Map _overrideValues;
private String _select;
/** Creates a new SphinxClient instance. */
public SphinxClient()
{
this("localhost", 9312);
}
/** Creates a new SphinxClient instance, with host:port specification. */
public SphinxClient(String host, int port)
{
_host = host;
_port = port;
_path = null;
_socket = null;
_offset = 0;
_limit = 20;
_mode = SPH_MATCH_EXTENDED2;
_sort = SPH_SORT_RELEVANCE;
_sortby = "";
_minId = 0;
_maxId = 0;
_filterCount = 0;
_rawFilters = new ByteArrayOutputStream();
_filters = new DataOutputStream(_rawFilters);
_groupBy = "";
_groupFunc = SPH_GROUPBY_DAY;
_groupSort = "@group desc";
_groupDistinct = "";
_maxMatches = 1000;
_cutoff = 0;
_retrycount = 0;
_retrydelay = 0;
_latitudeAttr = null;
_longitudeAttr = null;
_latitude = 0;
_longitude = 0;
_error = "";
_warning = "";
_connerror = false;
_timeout = 1000;
_reqs = new ArrayList();
_weights = null;
_indexWeights = new LinkedHashMap();
_fieldWeights = new LinkedHashMap();
_ranker = SPH_RANK_PROXIMITY_BM25;
_rankexpr = "";
_overrideTypes = new LinkedHashMap();
_overrideValues = new LinkedHashMap();
_select = "*";
}
/** Get last error message, if any. */
public String GetLastError()
{
return _error;
}
/** Get last warning message, if any. */
public String GetLastWarning()
{
return _warning;
}
/** Get last error flag (to tell network connection errors from searchd errors or broken responses). */
public boolean IsConnectError()
{
return _connerror;
}
/** Set searchd host and port to connect to. */
public void SetServer(String host, int port) throws SphinxException
{
myAssert ( host!=null && host.length()>0, "host name must not be empty" );
myAssert ( port>0 && port<65536, "port must be in 1..65535 range" );
_host = host;
_port = port;
}
/** Set server connection timeout (0 to remove), in milliseconds. */
public void SetConnectTimeout ( int timeout )
{
_timeout = Math.max ( timeout, 0 );
}
/** Internal method. Sanity check. */
private void myAssert ( boolean condition, String err ) throws SphinxException
{
if ( !condition )
{
_error = err;
throw new SphinxException ( err );
}
}
/** Internal method. String IO helper. */
private static void writeNetUTF8 ( DataOutputStream ostream, String str ) throws IOException
{
if ( str==null )
{
ostream.writeInt ( 0 );
return;
}
byte[] sBytes = str.getBytes ( "UTF-8" );
int iLen = sBytes.length;
ostream.writeInt ( iLen );
ostream.write ( sBytes );
}
/** Internal method. String IO helper. */
private static String readNetUTF8(DataInputStream istream) throws IOException
{
int iLen = istream.readInt();
byte[] sBytes = new byte [ iLen ];
istream.readFully ( sBytes );
return new String ( sBytes, "UTF-8");
}
/** Internal method. Unsigned int IO helper. */
private static long readDword ( DataInputStream istream ) throws IOException
{
long v = (long) istream.readInt ();
if ( v<0 )
v += 4294967296L;
return v;
}
/** Internal method. Connect to searchd and exchange versions. */
private Socket _Connect()
{
if ( _socket!=null )
return _socket;
_connerror = false;
Socket sock = null;
try
{
sock = new Socket ();
sock.setSoTimeout ( _timeout );
InetSocketAddress addr = new InetSocketAddress ( _host, _port );
sock.connect ( addr, _timeout );
DataInputStream sIn = new DataInputStream ( sock.getInputStream() );
int version = sIn.readInt();
if ( version<1 )
{
sock.close ();
_error = "expected searchd protocol version 1+, got version " + version;
return null;
}
DataOutputStream sOut = new DataOutputStream ( sock.getOutputStream() );
sOut.writeInt ( VER_MAJOR_PROTO );
} catch ( IOException e )
{
_error = "connection to " + _host + ":" + _port + " failed: " + e;
_connerror = true;
try
{
if ( sock!=null )
sock.close ();
} catch ( IOException e1 ) {}
return null;
}
return sock;
}
/** Internal method. Get and check response packet from searchd. */
private byte[] _GetResponse ( Socket sock )
{
/* connect */
DataInputStream sIn = null;
InputStream SockInput = null;
try
{
SockInput = sock.getInputStream();
sIn = new DataInputStream ( SockInput );
} catch ( IOException e )
{
_error = "getInputStream() failed: " + e;
return null;
}
/* read response */
byte[] response = null;
short status = 0, ver = 0;
int len = 0;
try
{
/* read status fields */
status = sIn.readShort();
ver = sIn.readShort();
len = sIn.readInt();
/* read response if non-empty */
if ( len<=0 )
{
_error = "invalid response packet size (len=" + len + ")";
return null;
}
response = new byte[len];
sIn.readFully ( response, 0, len );
/* check status */
if ( status==SEARCHD_WARNING )
{
DataInputStream in = new DataInputStream ( new ByteArrayInputStream ( response ) );
int iWarnLen = in.readInt ();
_warning = new String ( response, 4, iWarnLen );
System.arraycopy ( response, 4+iWarnLen, response, 0, response.length-4-iWarnLen );
} else if ( status==SEARCHD_ERROR )
{
_error = "searchd error: " + new String ( response, 4, response.length-4 );
return null;
} else if ( status==SEARCHD_RETRY )
{
_error = "temporary searchd error: " + new String ( response, 4, response.length-4 );
return null;
} else if ( status!=SEARCHD_OK )
{
_error = "searched returned unknown status, code=" + status;
return null;
}
} catch ( IOException e )
{
if ( len!=0 )
{
/* get trace, to provide even more failure details */
PrintWriter ew = new PrintWriter ( new StringWriter() );
e.printStackTrace ( ew );
ew.flush ();
ew.close ();
String sTrace = ew.toString ();
/* build error message */
_error = "failed to read searchd response (status=" + status + ", ver=" + ver + ", len=" + len + ", trace=" + sTrace +")";
} else
{
_error = "received zero-sized searchd response (searchd crashed?): " + e.getMessage();
}
return null;
} finally
{
if ( _socket==null )
{
try
{
if ( sIn!=null )
sIn.close();
if ( sock!=null && !sock.isConnected() )
sock.close();
} catch ( IOException e )
{
/* silently ignore close failures; nothing could be done anyway */
}
}
}
return response;
}
/** Internal method. Connect to searchd, send request, get response as DataInputStream. */
private DataInputStream _DoRequest ( int command, int version, ByteArrayOutputStream req )
{
/* connect */
Socket sock = _Connect();
if ( sock==null )
return null;
/* send request */
byte[] reqBytes = req.toByteArray();
try
{
DataOutputStream sockDS = new DataOutputStream ( sock.getOutputStream() );
sockDS.writeShort ( command );
sockDS.writeShort ( version );
sockDS.writeInt ( reqBytes.length );
sockDS.write ( reqBytes );
} catch ( Exception e )
{
_error = "network error: " + e;
_connerror = true;
return null;
}
/* get response */
byte[] response = _GetResponse ( sock );
if ( response==null )
return null;
/* spawn that tampon */
return new DataInputStream ( new ByteArrayInputStream ( response ) );
}
/** Set matches offset and limit to return to client, max matches to retrieve on server, and cutoff. */
public void SetLimits ( int offset, int limit, int max, int cutoff ) throws SphinxException
{
myAssert ( offset>=0, "offset must not be negative" );
myAssert ( limit>0, "limit must be positive" );
myAssert ( max>0, "max must be positive" );
myAssert ( cutoff>=0, "cutoff must not be negative" );
_offset = offset;
_limit = limit;
_maxMatches = max;
_cutoff = cutoff;
}
/** Set matches offset and limit to return to client, and max matches to retrieve on server. */
public void SetLimits ( int offset, int limit, int max ) throws SphinxException
{
SetLimits ( offset, limit, max, _cutoff );
}
/** Set matches offset and limit to return to client. */
public void SetLimits ( int offset, int limit) throws SphinxException
{
SetLimits ( offset, limit, _maxMatches, _cutoff );
}
/** Set maximum query time, in milliseconds, per-index, 0 means "do not limit". */
public void SetMaxQueryTime ( int maxTime ) throws SphinxException
{
myAssert ( maxTime>=0, "max_query_time must not be negative" );
_maxQueryTime = maxTime;
}
/** Set matching mode. DEPRECATED */
public void SetMatchMode(int mode) throws SphinxException
{
System.out.println ( "DEPRECATED: Do not call this method or, even better, use SphinxQL instead of an API\n" );
myAssert (
mode==SPH_MATCH_ALL ||
mode==SPH_MATCH_ANY ||
mode==SPH_MATCH_PHRASE ||
mode==SPH_MATCH_BOOLEAN ||
mode==SPH_MATCH_EXTENDED ||
mode==SPH_MATCH_FULLSCAN ||
mode==SPH_MATCH_EXTENDED2, "unknown mode value; use one of the SPH_MATCH_xxx constants" );
_mode = mode;
}
/** Set ranking mode. */
public void SetRankingMode ( int ranker, String rankexpr ) throws SphinxException
{
myAssert ( ranker>=0 && ranker<SPH_RANK_TOTAL, "unknown ranker value; use one of the SPH_RANK_xxx constants" );
_rankexpr = ( rankexpr==null ) ? "" : rankexpr;
_ranker = ranker;
}
/** Set sorting mode. */
public void SetSortMode ( int mode, String sortby ) throws SphinxException
{
myAssert (
mode==SPH_SORT_RELEVANCE ||
mode==SPH_SORT_ATTR_DESC ||
mode==SPH_SORT_ATTR_ASC ||
mode==SPH_SORT_TIME_SEGMENTS ||
mode==SPH_SORT_EXTENDED ||
mode==SPH_SORT_EXPR, "unknown mode value; use one of the available SPH_SORT_xxx constants" );
myAssert ( mode==SPH_SORT_RELEVANCE || ( sortby!=null && sortby.length()>0 ), "sortby string must not be empty in selected mode" );
_sort = mode;
_sortby = ( sortby==null ) ? "" : sortby;
}
/** Set per-field weights (all values must be positive). WARNING: DEPRECATED, use SetFieldWeights() instead. */
public void SetWeights(int[] weights) throws SphinxException
{
myAssert ( weights!=null, "weights must not be null" );
for (int i = 0; i < weights.length; i++) {
int weight = weights[i];
myAssert ( weight>0, "all weights must be greater than 0" );
}
_weights = weights;
}
/**
* Bind per-field weights by field name.
* @param fieldWeights hash which maps String index names to Integer weights
*/
public void SetFieldWeights ( Map fieldWeights ) throws SphinxException
{
/* FIXME! implement checks here */
_fieldWeights = ( fieldWeights==null ) ? new LinkedHashMap () : fieldWeights;
}
/**
* Bind per-index weights by index name (and enable summing the weights on duplicate matches, instead of replacing them).
* @param indexWeights hash which maps String index names to Integer weights
*/
public void SetIndexWeights ( Map indexWeights ) throws SphinxException
{
/* FIXME! implement checks here */
_indexWeights = ( indexWeights==null ) ? new LinkedHashMap () : indexWeights;
}
/** Set document IDs range to match. */
public void SetIDRange ( int min, int max ) throws SphinxException
{
myAssert ( min<=max, "min must be less or equal to max" );
_minId = min;
_maxId = max;
}
/** Set values filter. Only match records where attribute value is in given set. */
public void SetFilter ( String attribute, int[] values, boolean exclude ) throws SphinxException
{
myAssert ( values!=null && values.length>0, "values array must not be null or empty" );
myAssert ( attribute!=null && attribute.length()>0, "attribute name must not be null or empty" );
try
{
writeNetUTF8 ( _filters, attribute );
_filters.writeInt ( SPH_FILTER_VALUES );
_filters.writeInt ( values.length );
for ( int i=0; i<values.length; i++ )
_filters.writeLong ( values[i] );
_filters.writeInt ( exclude ? 1 : 0 );
} catch ( Exception e )
{
myAssert ( false, "IOException: " + e.getMessage() );
}
_filterCount++;
}
/** Set values filter. Only match records where attribute value is in given set. */
public void SetFilter ( String attribute, long[] values, boolean exclude ) throws SphinxException
{
myAssert ( values!=null && values.length>0, "values array must not be null or empty" );
myAssert ( attribute!=null && attribute.length()>0, "attribute name must not be null or empty" );
try
{
writeNetUTF8 ( _filters, attribute );
_filters.writeInt ( SPH_FILTER_VALUES );
_filters.writeInt ( values.length );
for ( int i=0; i<values.length; i++ )
_filters.writeLong ( values[i] );
_filters.writeInt ( exclude ? 1 : 0 );
} catch ( Exception e )
{
myAssert ( false, "IOException: " + e.getMessage() );
}
_filterCount++;
}
/** Set values filter with a single value (syntax sugar; see {@link #SetFilter(String,int[],boolean)}). */
public void SetFilter ( String attribute, int value, boolean exclude ) throws SphinxException
{
long[] values = new long[] { value };
SetFilter ( attribute, values, exclude );
}
/** Set values filter with a single value (syntax sugar; see {@link #SetFilter(String,int[],boolean)}). */
public void SetFilter ( String attribute, long value, boolean exclude ) throws SphinxException
{
long[] values = new long[] { value };
SetFilter ( attribute, values, exclude );
}
/** Set integer range filter. Only match records if attribute value is beetwen min and max (inclusive). */
public void SetFilterRange ( String attribute, long min, long max, boolean exclude ) throws SphinxException
{
myAssert ( min<=max, "min must be less or equal to max" );
try
{
writeNetUTF8 ( _filters, attribute );
_filters.writeInt ( SPH_FILTER_RANGE );
_filters.writeLong ( min );
_filters.writeLong ( max );
_filters.writeInt ( exclude ? 1 : 0 );
} catch ( Exception e )
{
myAssert ( false, "IOException: " + e.getMessage() );
}
_filterCount++;
}
/** Set integer range filter. Only match records if attribute value is beetwen min and max (inclusive). */
public void SetFilterRange ( String attribute, int min, int max, boolean exclude ) throws SphinxException
{
SetFilterRange ( attribute, (long)min, (long)max, exclude );
}
/** Set float range filter. Only match records if attribute value is beetwen min and max (inclusive). */
public void SetFilterFloatRange ( String attribute, float min, float max, boolean exclude ) throws SphinxException
{
myAssert ( min<=max, "min must be less or equal to max" );
try
{
writeNetUTF8 ( _filters, attribute );
_filters.writeInt ( SPH_FILTER_FLOATRANGE );
_filters.writeFloat ( min );
_filters.writeFloat ( max );
_filters.writeInt ( exclude ? 1 : 0 );
} catch ( Exception e )
{
myAssert ( false, "IOException: " + e.getMessage() );
}
_filterCount++;
}
/** Setup geographical anchor point. Required to use @geodist in filters and sorting; distance will be computed to this point. */
public void SetGeoAnchor ( String latitudeAttr, String longitudeAttr, float latitude, float longitude ) throws SphinxException
{
myAssert ( latitudeAttr!=null && latitudeAttr.length()>0, "longitudeAttr string must not be null or empty" );
myAssert ( longitudeAttr!=null && longitudeAttr.length()>0, "longitudeAttr string must not be null or empty" );
_latitudeAttr = latitudeAttr;
_longitudeAttr = longitudeAttr;
_latitude = latitude;
_longitude = longitude;
}
/** Set grouping attribute and function. */
public void SetGroupBy ( String attribute, int func, String groupsort ) throws SphinxException
{
myAssert (
func==SPH_GROUPBY_DAY ||
func==SPH_GROUPBY_WEEK ||
func==SPH_GROUPBY_MONTH ||
func==SPH_GROUPBY_YEAR ||
func==SPH_GROUPBY_ATTR ||
func==SPH_GROUPBY_ATTRPAIR, "unknown func value; use one of the available SPH_GROUPBY_xxx constants" );
_groupBy = attribute;
_groupFunc = func;
_groupSort = groupsort;
}
/** Set grouping attribute and function with default ("@group desc") groupsort (syntax sugar). */
public void SetGroupBy(String attribute, int func) throws SphinxException
{
SetGroupBy(attribute, func, "@group desc");
}
/** Set count-distinct attribute for group-by queries. */
public void SetGroupDistinct(String attribute)
{
_groupDistinct = attribute;
}
/** Set distributed retries count and delay. */
public void SetRetries ( int count, int delay ) throws SphinxException
{
myAssert ( count>=0, "count must not be negative" );
myAssert ( delay>=0, "delay must not be negative" );
_retrycount = count;
_retrydelay = delay;
}
/** Set distributed retries count with default (zero) delay (syntax sugar). */
public void SetRetries ( int count ) throws SphinxException
{
SetRetries ( count, 0 );
}
/**
* DEPRECATED: Set attribute values override (one override list per attribute).
* @param values maps Long document IDs to Int/Long/Float values (as specified in attrtype).
*/
public void SetOverride ( String attrname, int attrtype, Map values ) throws SphinxException
{
System.out.println ( "DEPRECATED: Do not call this method. Use SphinxQL REMAP() function instead.\n" );
myAssert ( attrname!=null && attrname.length()>0, "attrname must not be empty" );
myAssert ( attrtype==SPH_ATTR_INTEGER || attrtype==SPH_ATTR_TIMESTAMP || attrtype==SPH_ATTR_BOOL || attrtype==SPH_ATTR_FLOAT || attrtype==SPH_ATTR_BIGINT,
"unsupported attrtype (must be one of INTEGER, TIMESTAMP, BOOL, FLOAT, or BIGINT)" );
_overrideTypes.put ( attrname, new Integer ( attrtype ) );
_overrideValues.put ( attrname, values );
}
/** Set select-list (attributes or expressions), SQL-like syntax. */
public void SetSelect ( String select ) throws SphinxException
{
myAssert ( select!=null, "select clause string must not be null" );
_select = select;
}
/** Reset all currently set filters (for multi-queries). */
public void ResetFilters()
{
/* should we close them first? */
_rawFilters = new ByteArrayOutputStream();
_filters = new DataOutputStream(_rawFilters);
_filterCount = 0;
/* reset GEO anchor */
_latitudeAttr = null;
_longitudeAttr = null;
_latitude = 0;
_longitude = 0;
}
/** Clear groupby settings (for multi-queries). */
public void ResetGroupBy ()
{
_groupBy = "";
_groupFunc = SPH_GROUPBY_DAY;
_groupSort = "@group desc";
_groupDistinct = "";
}
/** Clear all attribute value overrides (for multi-queries). */
public void ResetOverrides ()
{
_overrideTypes.clear ();
_overrideValues.clear ();
}
/** Connect to searchd server and run current search query against all indexes (syntax sugar). */
public SphinxResult Query ( String query ) throws SphinxException
{
return Query ( query, "*", "" );
}
/** Connect to searchd server and run current search query against all indexes (syntax sugar). */
public SphinxResult Query ( String query, String index ) throws SphinxException
{
return Query ( query, index, "" );
}
/** Connect to searchd server and run current search query. */
public SphinxResult Query ( String query, String index, String comment ) throws SphinxException
{
myAssert ( _reqs==null || _reqs.size()==0, "AddQuery() and Query() can not be combined; use RunQueries() instead" );
AddQuery ( query, index, comment );
SphinxResult[] results = RunQueries();
_reqs = new ArrayList(); /* just in case it failed too early */
if ( results==null || results.length<1 )
return null; /* probably network error; error message should be already filled */
SphinxResult res = results[0];
_warning = res.warning;
_error = res.error;
if ( res==null || res.getStatus()==SEARCHD_ERROR )
return null;
return res;
}
/** Add new query with current settings to current search request. */
public int AddQuery ( String query, String index, String comment ) throws SphinxException
{
ByteArrayOutputStream req = new ByteArrayOutputStream();
/* build request */
try {
DataOutputStream out = new DataOutputStream(req);
out.writeInt(_offset);
out.writeInt(_limit);
out.writeInt(_mode);
out.writeInt(_ranker);
if ( _ranker == SPH_RANK_EXPR ) {
writeNetUTF8(out, _rankexpr);
}
out.writeInt(_sort);
writeNetUTF8(out, _sortby);
writeNetUTF8(out, query);
int weightLen = _weights != null ? _weights.length : 0;
out.writeInt(weightLen);
if (_weights != null) {
for (int i = 0; i < _weights.length; i++)
out.writeInt(_weights[i]);
}
writeNetUTF8(out, index);
out.writeInt(0);
out.writeInt(_minId);
out.writeInt(_maxId);
/* filters */
out.writeInt(_filterCount);
out.write(_rawFilters.toByteArray());
/* group-by, max matches, sort-by-group flag */
out.writeInt(_groupFunc);
writeNetUTF8(out, _groupBy);
out.writeInt(_maxMatches);
writeNetUTF8(out, _groupSort);
out.writeInt(_cutoff);
out.writeInt(_retrycount);
out.writeInt(_retrydelay);
writeNetUTF8(out, _groupDistinct);
/* anchor point */
if (_latitudeAttr == null || _latitudeAttr.length() == 0 || _longitudeAttr == null || _longitudeAttr.length() == 0) {
out.writeInt(0);
} else {
out.writeInt(1);
writeNetUTF8(out, _latitudeAttr);
writeNetUTF8(out, _longitudeAttr);
out.writeFloat(_latitude);
out.writeFloat(_longitude);
}
/* per-index weights */
out.writeInt(_indexWeights.size());
for (Iterator e = _indexWeights.keySet().iterator(); e.hasNext();) {
String indexName = (String) e.next();
Integer weight = (Integer) _indexWeights.get(indexName);
writeNetUTF8(out, indexName);
out.writeInt(weight.intValue());
}
/* max query time */
out.writeInt ( _maxQueryTime );
/* per-field weights */
out.writeInt ( _fieldWeights.size() );
for ( Iterator e=_fieldWeights.keySet().iterator(); e.hasNext(); )
{
String field = (String) e.next();
Integer weight = (Integer) _fieldWeights.get ( field );
writeNetUTF8 ( out, field );
out.writeInt ( weight.intValue() );
}
/* comment */
writeNetUTF8 ( out, comment );
/* overrides */
out.writeInt ( _overrideTypes.size() );
for ( Iterator e=_overrideTypes.keySet().iterator(); e.hasNext(); )
{
String attr = (String) e.next();
Integer type = (Integer) _overrideTypes.get ( attr );
Map values = (Map) _overrideValues.get ( attr );
writeNetUTF8 ( out, attr );
out.writeInt ( type.intValue() );
out.writeInt ( values.size() );
for ( Iterator e2=values.keySet().iterator(); e2.hasNext(); )
{
Long id = (Long) e2.next ();
out.writeLong ( id.longValue() );
switch ( type.intValue() )
{
case SPH_ATTR_FLOAT: out.writeFloat ( ( (Float) values.get ( id ) ).floatValue() ); break;
case SPH_ATTR_BIGINT: out.writeLong ( ( (Long)values.get ( id ) ).longValue() ); break;
default: out.writeInt ( ( (Integer)values.get ( id ) ).intValue() ); break;
}
}
}
/* select-list */
writeNetUTF8 ( out, _select );
/* done! */
out.flush ();
int qIndex = _reqs.size();
_reqs.add ( qIndex, req.toByteArray() );
return qIndex;
} catch ( Exception e )
{
myAssert ( false, "error in AddQuery(): " + e + ": " + e.getMessage() );
} finally
{
try
{
_filters.close ();
_rawFilters.close ();
} catch ( IOException e )
{
myAssert ( false, "error in AddQuery(): " + e + ": " + e.getMessage() );
}
}
return -1;
}
/** Run all previously added search queries. */
public SphinxResult[] RunQueries() throws SphinxException
{
if ( _reqs==null || _reqs.size()<1 )
{
_error = "no queries defined, issue AddQuery() first";
return null;
}
/* build the mega-request */
int nreqs = _reqs.size();
ByteArrayOutputStream reqBuf = new ByteArrayOutputStream();
try
{
DataOutputStream req = new DataOutputStream ( reqBuf );
/* its a client */
req.writeInt(0);
req.writeInt ( nreqs );
for ( int i=0; i<nreqs; i++ )
req.write ( (byte[]) _reqs.get(i) );
req.flush ();
} catch ( Exception e )
{
_error = "internal error: failed to build request: " + e;
return null;
}
DataInputStream in =_DoRequest ( SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, reqBuf );
if ( in==null )
return null;
SphinxResult[] results = new SphinxResult [ nreqs ];
_reqs = new ArrayList();