forked from o19s/splainer-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplainer-search.js
3829 lines (3248 loc) · 113 KB
/
splainer-search.js
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
angular.module('o19s.splainer-search', []);
'use strict';
// Executes a solr search and returns
// a set of queryDocs
angular.module('o19s.splainer-search')
.service('baseExplainSvc', [
'vectorSvc',
function explainSvc(vectorSvc) {
this.Explain = function(explJson, explFactory) {
var datExplain = this;
this.asJson = explJson;
this.realContribution = this.score = parseFloat(explJson.value);
this.realExplanation = this.description = explJson.description;
var details = [];
if (explJson.hasOwnProperty('details')) {
details = explJson.details;
}
this.children = [];
angular.forEach(details, function(detail) {
var expl = explFactory(detail);
if (expl) {
datExplain.children.push(expl);
}
});
/* Each explain defines influencers,
*
* whatever this explain feels should be
* plucked out of the explJson passed in as a list
* of things that explain it
* */
this.influencers = function() {
return [];
};
/* Each explain reports its contribution
* */
this.contribution = function() {
return this.realContribution;
};
/* Each explain reports a more human-readable form
* of the explain text that hopefully is less search geeky
* */
this.explanation = function() {
return this.realExplanation;
};
/* Once we get to "matches" we intend to
* stop, and the level below becomes heavily related to
* similarity implementations (how does the tf * idf calculation work)
* we'll call that out seperately to keep things sane
* */
this.hasMatch = function() {
return false;
};
/* Return my influencers as a vector
* where magnitude of each dimension is how
* much I am influenced by that influencer
*
* IE if I am a SumExplain, my vector is likely to be
* for matches x and y with scores a and y respectively
*
* a * x + b * y
*
* here a and b are constants, x and y are other
* matches to be recursively expanded
*
* */
this.vectorize = function() {
var rVal = vectorSvc.create();
// base vector is just a, no expansion farther down
// so any children's expansion will get ignored
rVal.set(this.explanation(), this.contribution());
return rVal;
};
var mergeInto = function(sink, source) {
for (var attrname in source) { sink[attrname] = source[attrname]; }
return sink;
};
this.matchDetails = function() {
var rVal = {};
angular.forEach(this.children, function(child) {
mergeInto(rVal, child.matchDetails());
});
return rVal;
};
/* A friendly, hiererarchical view
* of all the influencers
* */
var asStr = '';
var asRawStr = '';
this.toStr = function(depth) {
if (asStr === '') {
if (depth === undefined) {
depth = 0;
}
var prefix = new Array(2 * depth).join(' ');
var me = prefix + this.contribution() + ' ' + this.explanation() + '\n';
var childStrs = [];
angular.forEach(this.influencers(), function(child) {
childStrs.push(child.toStr(depth+1));
});
asStr = me + childStrs.join('\n');
}
return asStr;
};
this.rawStr = function() {
/* global JSON */
if (asRawStr === '') {
asRawStr = JSON.stringify(this.asJson);
}
return asRawStr;
};
};
}
]);
'use strict';
/* Some browsers and PhantomJS don't support bind, mozilla provides
* this implementation as a monkey patch on Function.prototype
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fbind
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof FNOP && oThis ? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
'use strict';
// Resolves a set of ids to Normal docs
angular.module('o19s.splainer-search')
.service('docResolverSvc', [
'ResolverFactory',
function docResolverSvc(ResolverFactory) {
this.createResolver = function(ids, settings, chunkSize) {
return new ResolverFactory(ids, settings, chunkSize);
};
}
]);
'use strict';
angular.module('o19s.splainer-search')
.service('esExplainExtractorSvc', [
'normalDocsSvc',
function esExplainExtractorSvc(normalDocsSvc) {
var self = this;
// Functions
self.docsWithExplainOther = docsWithExplainOther;
function docsWithExplainOther(docs, fieldSpec) {
var parsedDocs = [];
angular.forEach(docs, function(doc) {
var normalDoc = normalDocsSvc.createNormalDoc(fieldSpec, doc);
parsedDocs.push(normalDoc);
});
return parsedDocs;
}
}
]);
'use strict';
angular.module('o19s.splainer-search')
.service('esSearcherPreprocessorSvc', [
'queryTemplateSvc',
'defaultESConfig',
function esSearcherPreprocessorSvc(queryTemplateSvc, defaultESConfig) {
var self = this;
// Attributes
// field name since ES 5.0
self.fieldsParamNames = [ '_source'];
// Functions
self.prepare = prepare;
var replaceQuery = function(args, queryText) {
// Allows full override of query if a JSON friendly format is sent in
if (queryText instanceof Object) {
return queryText;
} else {
if (queryText) {
queryText = queryText.replace(/\\/g, '\\\\');
queryText = queryText.replace(/"/g, '\\\"');
}
var replaced = angular.toJson(args, true);
replaced = queryTemplateSvc.hydrate(replaced, queryText, {encodeURI: false, defaultKw: '\\"\\"'});
replaced = angular.fromJson(replaced);
return replaced;
}
};
var prepareHighlighting = function (args, fields) {
if ( angular.isDefined(fields) && fields !== null ) {
if ( fields.hasOwnProperty('fields') ) {
fields = fields.fields;
}
if ( fields.length > 0 ) {
var hl = { fields: {} };
angular.forEach(fields, function(fieldName) {
hl.fields[fieldName] = { };
});
return hl;
}
}
return {
fields: {
_all: {}
}
};
};
var preparePostRequest = function (searcher) {
var pagerArgs = angular.copy(searcher.args.pager);
if ( angular.isUndefined(pagerArgs) || pagerArgs === null ) {
pagerArgs = {};
}
var defaultPagerArgs = {
from: 0,
size: searcher.config.numberOfRows,
};
searcher.pagerArgs = angular.merge({}, defaultPagerArgs, pagerArgs);
delete searcher.args.pager;
var queryDsl = replaceQuery(searcher.args, searcher.queryText);
queryDsl.explain = true;
if ( angular.isDefined(searcher.fieldList) && searcher.fieldList !== null ) {
angular.forEach(self.fieldsParamNames, function(name) {
queryDsl[name] = searcher.fieldList;
});
}
if ( !queryDsl.hasOwnProperty('highlight') ) {
queryDsl.highlight = prepareHighlighting(searcher.args, queryDsl[self.fieldsParamNames[0]]);
}
searcher.queryDsl = queryDsl;
};
var prepareGetRequest = function (searcher) {
searcher.url = searcher.url + '?q=' + searcher.queryText;
var pagerArgs = angular.copy(searcher.args.pager);
delete searcher.args.pager;
if ( angular.isDefined(pagerArgs) && pagerArgs !== null ) {
searcher.url += '&from=' + pagerArgs.from;
searcher.url += '&size=' + pagerArgs.size;
} else {
searcher.url += '&size=' + searcher.config.numberOfRows;
}
};
function prepare (searcher) {
if (searcher.config === undefined) {
searcher.config = defaultESConfig;
} else {
// make sure config params that weren't passed through are set from
// the default config object.
searcher.config = angular.merge({}, defaultESConfig, searcher.config);
}
if ( searcher.config.apiMethod === 'post') {
preparePostRequest(searcher);
} else if ( searcher.config.apiMethod === 'get') {
prepareGetRequest(searcher);
}
}
}
]);
'use strict';
/*global URI*/
angular.module('o19s.splainer-search')
.service('esUrlSvc', [
function esUrlSvc() {
var self = this;
self.parseUrl = parseUrl;
self.buildDocUrl = buildDocUrl;
self.buildExplainUrl = buildExplainUrl;
self.buildUrl = buildUrl;
self.buildBaseUrl = buildBaseUrl;
self.setParams = setParams;
self.getHeaders = getHeaders;
self.isBulkCall = isBulkCall;
/**
*
* private method fixURLProtocol
* Adds 'http://' to the beginning of the URL if no protocol was specified.
*
*/
var protocolRegex = /^https{0,1}\:/;
function fixURLProtocol(url) {
if (!protocolRegex.test(url)) {
url = 'http://' + url;
}
return url;
}
/**
*
* Parses an ES URL of the form [http|https]://[username@password:][host][:port]/[collectionName]/_search
* Splits up the different parts of the URL.
*
*/
function parseUrl (url) {
url = fixURLProtocol(url);
var a = new URI(url);
var esUri = {
protocol: a.protocol(),
host: a.host(),
pathname: a.pathname(),
username: a.username(),
password: a.password(),
query: a.query(),
};
if (esUri.pathname.endsWith('/')) {
esUri.pathname = esUri.pathname.substring(0, esUri.pathname.length - 1);
}
return esUri;
}
/**
*
* Builds ES URL of the form [protocol]://[host][:port]/[index]/[type]/[id]
* for an ES document.
*
*/
function buildDocUrl (uri, doc) {
var index = doc._index;
var type = doc._type;
var id = doc._id;
var url = self.buildBaseUrl(uri);
url = url + '/' + index + '/' + type + '/' + id;
return url;
}
/**
*
* Builds ES URL of the form [protocol]://[host][:port]/[index]/[type]/[id]/_explain
* for an ES document.
*
*/
function buildExplainUrl (uri, doc) {
var docUrl = self.buildDocUrl(uri, doc);
var url = docUrl + '/_explain';
return url;
}
/**
*
* Builds ES URL for a search query.
* Adds any query params if present: /_search?from=10&size=10
*/
function buildUrl (uri) {
var self = this;
var url = self.buildBaseUrl(uri);
url = url + uri.pathname;
// Return original URL if no params to append.
if ( angular.isUndefined(uri.params) && angular.isUndefined(uri.query) ) {
return url;
}
var paramsAsStrings = [];
angular.forEach(uri.params, function(value, key) {
paramsAsStrings.push(key + '=' + value);
});
if ( angular.isDefined(uri.query) && uri.query !== '' ) {
paramsAsStrings.push(uri.query);
}
// Return original URL if no params to append.
if ( paramsAsStrings.length === 0 ) {
return url;
}
var finalUrl = url;
if (finalUrl.substring(finalUrl.length - 1) === '?') {
finalUrl += paramsAsStrings.join('&');
} else {
finalUrl += '?' + paramsAsStrings.join('&');
}
return finalUrl;
}
function buildBaseUrl (uri) {
var url = uri.protocol + '://';
url += (uri.host);
return url;
}
function setParams (uri, params) {
uri.params = params;
}
function getHeaders (uri) {
var headers = {};
if ( angular.isDefined(uri.username) && uri.username !== '' &&
angular.isDefined(uri.password) && uri.password !== '') {
var authorization = 'Basic ' + btoa(uri.username + ':' + uri.password);
headers = { 'Authorization': authorization };
}
return headers;
}
function isBulkCall (uri) {
return uri.pathname.endsWith('_msearch');
}
}
]);
'use strict';
// Factory for explains
// really ties the room together
angular.module('o19s.splainer-search')
.service('explainSvc', [
'baseExplainSvc',
'queryExplainSvc',
'simExplainSvc',
function explainSvc(baseExplainSvc, queryExplainSvc, simExplainSvc) {
var Explain = baseExplainSvc.Explain;
var ConstantScoreExplain = queryExplainSvc.ConstantScoreExplain;
var MatchAllDocsExplain = queryExplainSvc.MatchAllDocsExplain;
var WeightExplain = queryExplainSvc.WeightExplain;
var FunctionQueryExplain = queryExplainSvc.FunctionQueryExplain;
var DismaxTieExplain = queryExplainSvc.DismaxTieExplain;
var DismaxExplain = queryExplainSvc.DismaxExplain;
var SumExplain = queryExplainSvc.SumExplain;
var CoordExplain = queryExplainSvc.CoordExplain;
var ProductExplain = queryExplainSvc.ProductExplain;
var MinExplain = queryExplainSvc.MinExplain;
var EsFieldFunctionQueryExplain = queryExplainSvc.EsFieldFunctionQueryExplain;
var EsFuncWeightExplain = queryExplainSvc.EsFuncWeightExplain;
var FieldWeightExplain = simExplainSvc.FieldWeightExplain;
var QueryWeightExplain = simExplainSvc.QueryWeightExplain;
var DefaultSimTfExplain = simExplainSvc.DefaultSimTfExplain;
var DefaultSimIdfExplain = simExplainSvc.DefaultSimIdfExplain;
var ScoreExplain = simExplainSvc.ScoreExplain;
var meOrOnlyChild = function(explain) {
var infl = explain.influencers();
if (infl.length === 1) {
return infl[0]; //only child
} else {
return explain;
}
};
var replaceBadJson = function(explJson) {
var explJsonIfBad = {
details: [],
description: 'no explain for doc',
value: 0.0,
match: true
};
if (!explJson) {
return explJsonIfBad;
} else {
return explJson;
}
};
var tieRegex = /max plus ([0-9.]+) times/;
var prefixRegex = /\:.*?\*(\^.+?)?, product of/;
var createExplain = function(explJson) {
explJson = replaceBadJson(explJson);
var base = new Explain(explJson, createExplain);
var description = explJson.description;
var details = [];
var IGNORED = null;
var tieMatch = description.match(tieRegex);
var prefixMatch = description.match(prefixRegex);
if (explJson.hasOwnProperty('details')) {
details = explJson.details;
}
if (description.startsWith('score(')) {
ScoreExplain.prototype = base;
return new ScoreExplain(explJson);
}
if (description.startsWith('tf(')) {
DefaultSimTfExplain.prototype = base;
return new DefaultSimTfExplain(explJson);
}
else if (description.startsWith('idf(')) {
DefaultSimIdfExplain.prototype = base;
return new DefaultSimIdfExplain(explJson);
}
else if (description.startsWith('fieldWeight')) {
FieldWeightExplain.prototype = base;
return new FieldWeightExplain(explJson);
}
else if (description.startsWith('queryWeight')) {
QueryWeightExplain.prototype = base;
return new QueryWeightExplain(explJson);
}
if (description.startsWith('ConstantScore')) {
ConstantScoreExplain.prototype = base;
return new ConstantScoreExplain(explJson);
}
else if (description.startsWith('MatchAllDocsQuery')) {
MatchAllDocsExplain.prototype = base;
return new MatchAllDocsExplain(explJson);
}
else if (description.startsWith('weight(')) {
WeightExplain.prototype = base;
return new WeightExplain(explJson);
}
else if (description.startsWith('FunctionQuery')) {
FunctionQueryExplain.prototype = base;
return new FunctionQueryExplain(explJson);
}
else if (description.startsWith('Function for field')) {
EsFieldFunctionQueryExplain.prototype = base;
return new EsFieldFunctionQueryExplain(explJson);
}
else if (prefixMatch && prefixMatch.length > 1) {
WeightExplain.prototype = base;
return new WeightExplain(explJson);
}
else if (description.startsWith('match on required clause') || description.startsWith('match filter')) {
return IGNORED; // because Elasticsearch funciton queries filter when they apply boosts (this doesn't matter in scoring)
}
else if (description.startsWith('queryBoost')) {
if (explJson.value === 1.0) {
return IGNORED; // because Elasticsearch function queries always add 'queryBoost' of 1, even when boost not specified
}
}
else if (description.hasSubstr('constant score') && description.hasSubstr('no function provided')) {
return IGNORED;
}
else if (description === 'weight') {
EsFuncWeightExplain.prototype = base;
return new EsFuncWeightExplain(explJson);
}
else if (tieMatch && tieMatch.length > 1) {
var tie = parseFloat(tieMatch[1]);
DismaxTieExplain.prototype = base;
return new DismaxTieExplain(explJson, tie);
}
else if (description.hasSubstr('max of')) {
DismaxExplain.prototype = base;
return meOrOnlyChild(new DismaxExplain(explJson));
}
else if (description.hasSubstr('sum of')) {
SumExplain.prototype = base;
return meOrOnlyChild(new SumExplain(explJson));
}
else if (description.hasSubstr('Math.min of')) {
MinExplain.prototype = base;
return meOrOnlyChild(new MinExplain(explJson));
}
else if (description.hasSubstr('min of')) {
MinExplain.prototype = base;
return meOrOnlyChild(new MinExplain(explJson));
}
else if (description.hasSubstr('score mode [multiply]')) {
ProductExplain.prototype = base;
return meOrOnlyChild(new ProductExplain(explJson));
}
else if (description.hasSubstr('product of')) {
var coordExpl = null;
if (details.length === 2) {
angular.forEach(details, function(detail) {
if (detail.description.startsWith('coord(')) {
CoordExplain.prototype = base;
coordExpl = new CoordExplain(explJson, parseFloat(detail.value));
}
});
}
if (coordExpl !== null) {
return coordExpl;
} else {
ProductExplain.prototype = base;
return meOrOnlyChild(new ProductExplain(explJson));
}
}
return base;
};
this.createExplain = function(explJson) {
return createExplain(explJson);
};
}
]);
'use strict';
angular.module('o19s.splainer-search')
.service('fieldSpecSvc', [
function fieldSpecSvc() {
var addFieldOfType = function(fieldSpec, fieldType, fieldName) {
if (['f', 'func', 'function'].includes(fieldType)) {
if (!fieldSpec.hasOwnProperty('functions')) {
fieldSpec.functions = [];
}
// a function query function:foo is really foo:$foo
if (fieldName.startsWith('$')) {
fieldName = fieldName.slice(1);
}
fieldName = fieldName + ':$' + fieldName;
fieldSpec.functions.push(fieldName);
}
if (['highlight', 'hl'].includes(fieldType)) {
if (!fieldSpec.hasOwnProperty('highlights')) {
fieldSpec.highlights = [];
}
fieldSpec.highlights.push(fieldName);
}
if (fieldType === 'media') {
if (!fieldSpec.hasOwnProperty('embeds')) {
fieldSpec.embeds = [];
}
fieldSpec.embeds.push(fieldName);
}
if (fieldType === 'sub') {
if (!fieldSpec.hasOwnProperty('subs')) {
fieldSpec.subs = [];
}
if (fieldSpec.subs !== '*') {
fieldSpec.subs.push(fieldName);
}
if (fieldName === '*') {
fieldSpec.subs = '*';
}
}
else if (!fieldSpec.hasOwnProperty(fieldType)) {
fieldSpec[fieldType] = fieldName;
}
fieldSpec.fields.push(fieldName);
};
// Populate field spec from a field spec string
var populateFieldSpec = function(fieldSpec, fieldSpecStr) {
var fieldSpecs = fieldSpecStr.split('+').join(' ').split(/[\s,]+/);
angular.forEach(fieldSpecs, function(aField) {
var specElements = aField.split(':');
var fieldTypes = null;
var fieldName = null;
if (specElements.length === 1) {
fieldName = specElements[0];
if (fieldSpec.hasOwnProperty('title')) {
fieldTypes = ['sub'];
}
else {
fieldTypes = ['title'];
}
} else if (specElements.length > 1) {
fieldName = specElements.pop();
fieldTypes = specElements;
}
if (fieldTypes && fieldName) {
angular.forEach(fieldTypes, function(fieldType) {
addFieldOfType(fieldSpec, fieldType, fieldName);
});
}
});
};
var FieldSpec = function(fieldSpecStr) {
this.fields = [];
this.fieldSpecStr = fieldSpecStr;
populateFieldSpec(this, fieldSpecStr);
if (!this.hasOwnProperty('id')) {
this.id = 'id';
this.fields.push('id');
}
if (!this.hasOwnProperty('title')) {
this.title = this.id;
}
this.fieldList = function() {
if (this.hasOwnProperty('subs') && this.subs === '*') {
return '*';
}
var rVal = [this.id];
this.forEachField(function(fieldName) {
rVal.push(fieldName);
});
return rVal;
};
this.highlightFieldList = function() {
return this.highlights;
};
// Execute innerBody for each (non id) field
this.forEachField = function(innerBody) {
if (this.hasOwnProperty('title')) {
innerBody(this.title);
}
if (this.hasOwnProperty('thumb')) {
innerBody(this.thumb);
}
angular.forEach(this.embeds, function(embed) {
innerBody(embed);
});
angular.forEach(this.highlights, function(hl) {
innerBody(hl);
});
angular.forEach(this.subs, function(sub) {
innerBody(sub);
});
angular.forEach(this.functions, function(func) {
innerBody(func);
});
};
};
var transformFieldSpec = function(fieldSpecStr) {
var defFieldSpec = 'id:id title:id *';
if (fieldSpecStr === null || fieldSpecStr.trim().length === 0) {
return defFieldSpec;
}
var fieldSpecs = fieldSpecStr.split(/[\s,]+/);
if (fieldSpecs[0] === '*') {
return defFieldSpec;
}
return fieldSpecStr;
};
this.createFieldSpec = function(fieldSpecStr) {
fieldSpecStr = transformFieldSpec(fieldSpecStr);
return new FieldSpec(fieldSpecStr);
};
}
]);
'use strict';
// Deals with normalizing documents from the search engine
// into a canonical representation, ie
// each doc has an id, a title, possibly a thumbnail field
// and possibly a list of sub fields
angular.module('o19s.splainer-search')
.service('normalDocsSvc', [
'explainSvc',
function normalDocsSvc(explainSvc) {
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'\"': '"',
'\'': ''',
'/': '/'
};
var escapeHtml = function(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
};
//
// Takes an array of keys and fetches the nested value
// by traversing the object map in parallel as the list of keys.
//
// @param obj, Object, the object we want to fetch value from.
// @param keys, Array, the list of keys.
//
// Example:
// obj: { a: { b: 'c' } }
// keys: [ 'a', 'b' ]
// returns: obj['a']['b'] => c
//
var multiIndex = function(obj, keys) {
if (keys.length === 0) {
return obj;
} else if (Array.isArray(obj)) {
return obj.map(function(child) {
return multiIndex(child, keys);
});
} else {
return multiIndex(obj[keys[0]], keys.slice(1));
}
};
//
// Takes a key that has a dot in it, and tests if the name of the property includes
// the dot, or if this is dot notation for traversing a nested object or array of objects.
//
// @param obj, Object, the object we want to fetch value from.
// @param keys, String, the dot notation of the keys.
//
// Example:
// obj: { a: { b: 'c' } }
// keys: 'a.b'
// returns: obj['a']['b'] => c
//
var pathIndex = function(obj, keys) {
if (obj.hasOwnProperty(keys)){
return obj[keys];
}
else {
return multiIndex(obj, keys.split('.'));
}
};
var assignSingleField = function(normalDoc, doc, field, toProperty) {
if ( /\./.test(field) ) {
try {
var value = pathIndex(doc, field);
normalDoc[toProperty] = '' + value;
} catch (e) {
normalDoc[toProperty] = '';
}
} else if ( doc.hasOwnProperty(field) ) {
normalDoc[toProperty] = '' + doc[field];
}
};
var fieldDisplayName = function(funcFieldQuery) {
// to Solr this is sent as foo:$foo, we just want to display "foo"
return funcFieldQuery.split(':')[0];
};
var assignEmbeds = function(normalDoc, doc, fieldSpec) {
angular.forEach(fieldSpec.embeds, function (embedField) {
normalDoc.embeds[embedField] = doc[embedField];
});
};
var assignSubs = function(normalDoc, doc, fieldSpec) {
var parseValue = function(value) {
if ( typeof value === 'object' ) {
return value;
} else {
return '' + value;
}
};
if (fieldSpec.subs === '*') {
angular.forEach(doc, function(value, fieldName) {
if (typeof(value) !== 'function') {
if (fieldName !== fieldSpec.id && fieldName !== fieldSpec.title &&
fieldName !== fieldSpec.thumb) {
normalDoc.subs[fieldName] = parseValue(value);
}
}
});
}
else {
angular.forEach(fieldSpec.subs, function(subFieldName) {
if ( /\./.test(subFieldName) ) {
try {
var value = pathIndex(doc, subFieldName);
normalDoc.subs[subFieldName] = parseValue(value);
} catch (e) {
console.error(e);
normalDoc.subs[subFieldName] = '';
}
} else if ( doc.hasOwnProperty(subFieldName) ) {
normalDoc.subs[subFieldName] = parseValue(doc[subFieldName]);
}
});
angular.forEach(fieldSpec.functions, function(functionField) {
// for foo:$foo, look for foo
var dispName = fieldDisplayName(functionField);
if (doc.hasOwnProperty(dispName)) {
normalDoc.subs[dispName] = parseValue(doc[dispName]);
}
});
angular.forEach(fieldSpec.highlights, function(hlField) {
if (fieldSpec.title !== hlField) {
normalDoc.subs[hlField] = parseValue(doc[hlField]);
}
});
}
};
var assignFields = function(normalDoc, doc, fieldSpec) {
assignSingleField(normalDoc, doc, fieldSpec.id, 'id');
assignSingleField(normalDoc, doc, fieldSpec.title, 'title');
assignSingleField(normalDoc, doc, fieldSpec.thumb, 'thumb');
normalDoc.titleField = fieldSpec.title;
normalDoc.embeds = {};
assignEmbeds(normalDoc, doc, fieldSpec);
normalDoc.subs = {};
assignSubs(normalDoc, doc, fieldSpec);
};
// A document within a query
var NormalDoc = function(fieldSpec, doc) {
this.doc = doc;
assignFields(this, this.doc.origin(), fieldSpec);
var hasThumb = false;
if (this.hasOwnProperty('thumb')) {
hasThumb = true;
}
this.subsList = [];
var thisNormalDoc = this;
angular.forEach(this.subs, function(subValue, subField) {
var expanded = {field: subField, value: subValue};
thisNormalDoc.subsList.push(expanded);
});
this.hasThumb = function() {
return hasThumb;
};
this._url = function() {
return this.doc._url(fieldSpec.id, this.id);
};
};
var getHighlightSnippet = function(aDoc, docId, subFieldName, subFieldValue, hlPre, hlPost) {
var snip = aDoc.highlight(
docId,
subFieldName,
hlPre,
hlPost
);
if ( null === snip || undefined === snip || '' === snip ) {
snip = escapeHtml(subFieldValue.slice(0, 200));
}
return snip;
};
// layer on highlighting features
var snippitable = function(doc) {
var aDoc = doc.doc;
var lastSubSnips = {};