forked from cuent/ngSolr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngsolr.js
3428 lines (3068 loc) · 122 KB
/
ngsolr.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
'use strict';
/*---------------------------------------------------------------------------*/
/* Application */
var app = angular.module('ngSolr', ['ngRoute','ngSanitize']);
// Application configuration
app.constant('Cfg', {
'api': 'api/data/',
'env': [ 'development','staging','production']
});
// Solr query defaults
app.constant('Solr', {
defaultQuery: function(query) {
var f = query.createFacet('location_0_coordinate', '*');
query.addFacet(f);
query.setOption('fl', '*');
query.setOption('rows', '5000');
query.setOption('sort', 'title+asc');
query.setOption('wt', 'json');
query.setUserQuery('*:*');
return query;
}
});
//// Reconfigure the default search query so that we only return those records
//// that have location coordinate values.
//var m = angular.module('Solr');
//m.config(['SolrSearchServiceProvider', function(SolrSearchServiceProvider) {
// var defaultQuery = function(query) {
// var f = query.createFacet('location_0_coordinate', '*');
// query.addFacet(f);
// query.setOption('fl', '*');
// query.setOption('json.wrf', 'JSON_CALLBACK');
// query.setOption('rows', '5000');
// query.setOption('sort', 'title+asc');
// query.setOption('wt', 'json');
// query.setUserQuery('*:*');
// return query;
// };
// SolrSearchServiceProvider.setDefaultQuery(defaultQuery);
//}]);
/**
* Define application routes.
* @see http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm
*/
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:query', { event: '/query' }).
otherwise({ event: '/' });
}]);
/* jshint camelcase:false */
/**
* Date facet controller filters a query by year range, displays controls to
* set the start/end dates.
* @param $scope Controller scope
* @param $attrs
* @param $location
* @param $route
* @param $routeParams
* @param SolrSearchService Solr search service
* @param Utils Utilities module
*/
angular
.module('ngSolr')
.controller('DateFacetController',
['$scope','$attrs','$location','$route','$routeParams','SolrSearchService','Utils',
function ($scope, $attrs, $location, $route, $routeParams, SolrSearchService, Utils) {
var date, dateRange, endDateQuery, endDateResults, end_value, end_year,
f, hash, i, item, query, start_value, start_year, startDateQuery,
startDateResults, yearEnd, yearStart;
// for tracking dates during update
$scope._endDate = 0;
$scope._startDate = 0;
// end date
$scope.endDate = 0;
// facet field name
$scope.endDateField = 'toDate';
// end date query name
$scope.endDateQueryName = 'endDateQuery';
// url to solr core
$scope.source = undefined;
// start date
$scope.startDate = 0;
// facet field name
$scope.startDateField = 'fromDate';
// start date query name
$scope.startDateQueryName = 'startDateQuery';
// update the facet list during init
$scope.updateOnInit = true;
// user query
$scope.userquery = '*:*';
//////////////////////////////////////////////////////////////////////////
/**
* Build the Solr date range constraint string. The date range will be
* inclusive such that all entities that existing within the specified
* date range will be returned.
* @param StartDateField
* @param StartDate
* @param EndDateField
* @param EndDate
*/
$scope.getDateRangeConstraint = function(StartDateField, StartDate, EndDateField, EndDate) {
yearStart = '-01-01T00:00:00Z';
yearEnd = '-12-31T23:59:59Z';
// ISSUE #26 +(startDateField:[* TO userEndDate] AND endDateField:[userStartDate TO *])
// ISSUE #20 the date query needs to be specified using a set of field queries
dateRange = '+(';
dateRange += StartDateField + ':[ * TO ' + EndDate + yearEnd + ' ]';
dateRange += ' AND ';
dateRange += EndDateField + ':[ ' + StartDate + yearStart + ' TO * ]';
dateRange += ')';
return dateRange;
};
/**
* Get the first date in the item list.
* @param Items List of items
* @param FieldName Date field
*/
$scope.getFirstDateRecord = function(Items, FieldName) {
if (Items && Items.docs && Items.docs.length > 0) {
item = Items.docs[0];
date = item[FieldName];
if (date !== undefined) {
i = date.indexOf('-');
return date.substring(0, i);
}
}
return 0;
};
/**
* Handle update on end date query.
*/
$scope.handleEndDateQueryUpdate = function() {
endDateResults = SolrSearchService.getResponse($scope.endDateQueryName);
if (endDateResults) {
$scope._endDate = $scope.getFirstDateRecord(endDateResults, $scope.endDateField);
$scope.endDate = $scope.getFirstDateRecord(endDateResults, $scope.endDateField);
}
};
/**
* Update the start date field.
*/
$scope.handleStartDateQueryUpdate = function() {
startDateResults = SolrSearchService.getResponse($scope.startDateQueryName);
if (startDateResults) {
$scope._startDate = $scope.getFirstDateRecord(startDateResults, $scope.startDateField);
$scope.startDate = $scope.getFirstDateRecord(startDateResults, $scope.startDateField);
}
};
/**
* Handle route update event.
*/
$scope.handleUpdate = function() {
hash = ($routeParams.query || '');
// get the existing query or create a default query if none exists
if (hash) {
query = SolrSearchService.getQueryFromHash(hash, $scope.source);
} else {
query = SolrSearchService.createQuery($scope.source);
}
// get the earliest date in the index. if there is an existing start
// date value query then use that instead.
f = query.getFacet($scope.endDateField);
if (f) {
// process the facet value so that we end up with only the year
// [1800-01-01T00:00:00Z TO *]
start_year = f.value.replace('[','').replace('-01-01T00:00:00Z TO *]','');
$scope._startDate = start_year;
$scope.startDate = start_year;
$scope.updateFlag += 1 ;
} else {
startDateQuery = SolrSearchService.createQuery($scope.source);
startDateQuery.setOption('fl', $scope.startDateField);
startDateQuery.setOption('rows', '1');
startDateQuery.setOption('sort', $scope.startDateField + ' asc');
startDateQuery.setUserQuery($scope.userquery);
SolrSearchService.setQuery($scope.startDateQueryName, startDateQuery);
SolrSearchService.updateQuery($scope.startDateQueryName);
}
// get the oldest date in the index. if there is an existing end data
// query use it, otherwise create a new query to get the date.
f = query.getFacet($scope.startDateField);
if (f) {
// need to process the value portion
// [* TO 2014-12-31T23:59:59Z]
end_year = f.value.replace('[* TO ','').replace('-12-31T23:59:59Z]','');
$scope._endDate = end_year;
$scope.endDate = end_year;
$scope.updateFlag += 1 ;
} else {
endDateQuery = SolrSearchService.createQuery($scope.source);
endDateQuery.setOption('fl', $scope.endDateField);
endDateQuery.setOption('rows', '1');
endDateQuery.setOption('sort', $scope.endDateField + ' desc');
endDateQuery.setUserQuery($scope.userquery);
SolrSearchService.setQuery($scope.endDateQueryName, endDateQuery);
SolrSearchService.updateQuery($scope.endDateQueryName);
}
};
/**
* Initialize the controller. Create queries to determine the start and
* end date values for the current query.
*/
$scope.init = function() {
// apply configured attributes
Utils.applyAttributes($attrs, $scope);
// handle location change event, update query results
$scope.$on('$routeChangeSuccess', function() {
$scope.handleUpdate();
});
// listen for updates on queries
$scope.$on($scope.startDateQueryName, function () {
$scope.handleStartDateQueryUpdate();
});
$scope.$on($scope.endDateQueryName, function () {
$scope.handleEndDateQueryUpdate();
});
};
/**
* Set a date range constraint on the target query.
*/
$scope.submit = function() {
// if the start date is greater than the end date, reset the date range
// to the original values and ignore the update request
if ($scope.startDate > $scope.endDate) {
// @todo we should signal the error to the user through the widget
$scope.endDate = $scope._endDate;
$scope.startDate = $scope._startDate;
return;
}
// get the current location
hash = ($routeParams.query || '');
if (hash) {
query = SolrSearchService.getQueryFromHash(hash, $scope.source);
} else {
query = SolrSearchService.createQuery($scope.source);
}
// remove any existing date facets
query.removeFacet($scope.startDateField);
query.removeFacet($scope.endDateField);
// create new date facets
start_value = '[* TO ' + $scope.endDate + '-12-31T23:59:59Z]';
end_value = '[' + $scope.startDate + '-01-01T00:00:00Z TO *]';
f = query.createFacet($scope.startDateField, start_value);
query.addFacet(f);
f = query.createFacet($scope.endDateField, end_value);
query.addFacet(f);
// change window location
hash = query.getHash();
$location.path(hash);
};
// initialize the controller
$scope.init();
}]);
/* global d3 */
/* jshint loopfunc:true */
/**
* Date facet controller filters a query by year range, displays controls to
* set the start/end dates, displays a histogram control to both view and
* filter date by year range.
* @param $scope Controller scope
* @param $attrs
* @param $location
* @param $log Log service
* @param $route
* @param $routeParams
* @param SolrSearchService Solr search service
* @param Utils Utilities module
*
* @todo the method of fetching dates should use the .then() method of data retrieval for the start/end dates
* @todo update to reflect the current date range, if such a facet exists
*/
angular
.module('ngSolr')
.controller('DateFacetHistogramController',
['$scope','$attrs','$location','$log','$route','$routeParams','SolrSearchService','Utils',
function ($scope, $attrs, $location, $log, $route, $routeParams, SolrSearchService, Utils) {
var bin, count, date, endDateResults, i, item, query, startDateResults, userquery;
// for tracking dates during histogram update
$scope._endDate = 0;
$scope._startDate = 0;
// end date
$scope.endDate = 0;
// facet field name
$scope.endDateField = 'toDate';
// end date query name
$scope.endDateQueryName = 'endDateQuery';
// histogram data
$scope.histogram = [];
// chart height
$scope.histogramHeight = 100;
// maximum number of histogram bins
$scope.histogramMaxBins = 10;
// histogram query name
$scope.histogramQueryName = 'histogramQuery';
// chart width
$scope.histogramWidth = 240;
// url to solr core
$scope.source = undefined;
// start date
$scope.startDate = 0;
// facet field name
$scope.startDateField = 'fromDate';
// start date query name
$scope.startDateQueryName = 'startDateQuery';
// named query to filter
$scope.target = SolrSearchService.defaultQueryName;
// flag used to track update process (-2 started, -1 partially done, 0 complete)
$scope.updateFlag = 0;
// update the histogram
$scope.updateHistogram = true;
// update the facet list during init
$scope.updateOnInit = false;
// update the date range to reflect the target query results
$scope.updateOnTargetChange = true;
//////////////////////////////////////////////////////////////////////////
/**
* Get the first date in the item list.
* @param Items List of items
* @param FieldName Date field
*/
$scope.getFirstDateRecord = function(Items, FieldName) {
if (Items && Items.docs && Items.docs.length > 0) {
item = Items.docs[0];
date = item[FieldName];
if (date !== undefined) {
i = date.indexOf('-');
return date.substring(0,i);
}
}
return 0;
};
/**
* Handle update on end date query.
*/
$scope.handleEndDateQueryUpdate = function() {
endDateResults = SolrSearchService.getResponse($scope.endDateQueryName);
if (endDateResults) {
$scope._endDate = $scope.getFirstDateRecord(endDateResults,$scope.endDateField);
$scope.endDate = $scope.getFirstDateRecord(endDateResults,$scope.endDateField);
}
// update the histogram after start/end dates have been updated
$scope.updateFlag++;
if ($scope.updateHistogram && $scope.updateFlag === 0) {
$scope.updateHistogram();
}
};
/**
* Handle update on the histogram query.
*/
$scope.handleHistogramQueryUpdate = function(Event) {
// get the bin number
i = Event.name.indexOf('_');
bin = Event.name.substring(i+1,Event.name.length);
// set the bin value
query = SolrSearchService.getQuery(Event.name);
count = query.response.numFound;
$scope.histogram[bin].count = count;
// update the chart
$scope.updateHistogramChart();
};
/**
* Update the start date field.
*/
$scope.handleStartDateQueryUpdate = function() {
startDateResults = SolrSearchService.getResponse($scope.startDateQueryName);
if (startDateResults) {
$scope._startDate = $scope.getFirstDateRecord(startDateResults,$scope.startDateField);
$scope.startDate = $scope.getFirstDateRecord(startDateResults,$scope.startDateField);
}
// update the histogram after start/end dates have been updated
$scope.updateFlag++;
if ($scope.updateHistogram && $scope.updateFlag === 0) {
$scope.updateHistogram();
}
};
/**
* Handle update event from the target query. Update the facet list to
* reflect the target query result set.
*/
$scope.handleTargetQueryUpdate = function() {
query = SolrSearchService.getQuery($scope.target);
userquery = query.getUserQuery();
// change the start date user query
query = SolrSearchService.getQuery($scope.startDateQueryName);
query.setUserQuery(userquery);
// change the end date user query
query = SolrSearchService.getQuery($scope.endDateQueryName);
query.setUserQuery(userquery);
// update queries
$scope.updateFlag = -2;
SolrSearchService.updateQuery($scope.startDateQueryName);
SolrSearchService.updateQuery($scope.endDateQueryName);
};
/**
* Initialize the controller. We create queries to determine the start and
* end date values. Once we have both of those values in hand, we then
* build a histogram of documents by date range.
*/
$scope.init = function() {
// apply configured attributes
Utils.applyAttributes($attrs, $scope);
// handle location change event, update query results
$scope.$on('$routeChangeSuccess', function() {
$scope.query = ($routeParams.query || '');
if ($scope.query) {
var query = SolrSearchService.getQueryFromHash($scope.query, $scope.source);
$scope.userquery = query.getUserQuery();
}
// build a query that will fetch the earliest date in the list
var startDateQuery = SolrSearchService.createQuery();
startDateQuery.setOption('fl', $scope.startDateField);
startDateQuery.setOption('rows','1');
startDateQuery.setOption('sort',$scope.startDateField + ' asc');
startDateQuery.setUserQuery($scope.userquery);
SolrSearchService.setQuery($scope.startDateQueryName, startDateQuery);
// build a query that will fetch the latest date in the list
var endDateQuery = SolrSearchService.createQuery();
endDateQuery.setOption('fl', $scope.endDateField);
endDateQuery.setOption('rows','1');
endDateQuery.setOption('sort',$scope.endDateField + ' desc');
endDateQuery.setUserQuery($scope.userquery);
SolrSearchService.setQuery($scope.endDateQueryName, endDateQuery);
// if we should update the date list during init
if ($scope.updateOnInit) {
$scope.updateFlag = -2;
SolrSearchService.updateQuery($scope.startDateQueryName);
SolrSearchService.updateQuery($scope.endDateQueryName);
}
});
// listen for updates on queries
$scope.$on($scope.startDateQueryName, function() {
$scope.handleStartDateQueryUpdate();
});
$scope.$on($scope.endDateQueryName, function() {
$scope.handleEndDateQueryUpdate();
});
};
/**
* Set a date range constraint on the target query.
*/
$scope.submit = function() {
if ($scope.startDate <= $scope.endDate) {
var query = SolrSearchService.getQuery($scope.target);
if (query) {
var dateRange = $scope.getDateRangeConstraint($scope.startDateField,$scope.startDate,$scope.endDateField,$scope.endDate);
query.setQueryParameter('dateRange',dateRange);
SolrSearchService.updateQuery($scope.target);
}
} else {
// set the values back to the prior state
$scope.endDate = $scope._endDate;
$scope.startDate = $scope._startDate;
$log.info('WARNING: start date is greater than end date');
}
};
/**
* Update the histogram data.
*/
$scope.updateHistogram = function () {
var bin, binRange, dateRange, end, histogramQuery, histogramQueryName, i, range, start;
// generate the bin query values
$scope.histogram = [];
range = Math.ceil($scope.endDate - $scope.startDate);
binRange = Math.ceil(range / $scope.histogramMaxBins);
for (i=0;i<$scope.histogramMaxBins;i++) {
start = Number($scope.startDate) + (binRange * i);
end = start + binRange;
bin = {};
bin.start = start;
bin.end = (end > $scope.endDate) ? $scope.endDate : end;
bin.label = start + ' to ' + bin.end;
bin.count = (10 * i) + 5; // a placeholder for testing -- the actual query count value should go here
$scope.histogram.push(bin);
}
// generate the histogram queries
for (i=0;i<$scope.histogram.length;i++) {
bin = $scope.histogram[i];
// create histogram query
histogramQuery = SolrSearchService.createQuery();
histogramQueryName = $scope.histogramQueryName + '_' + i;
dateRange = $scope.getDateRangeConstraint($scope.startDateField, bin.start, $scope.endDateField, bin.end);
histogramQuery.setOption('rows','0');
histogramQuery.setQueryParameter('dateRange',dateRange);
SolrSearchService.setQuery(histogramQueryName,histogramQuery);
// listen for changes on the query
$scope.$on(histogramQueryName, function(histogramQueryName) {
$scope.handleHistogramQueryUpdate(histogramQueryName);
});
// update the query
SolrSearchService.updateQuery(histogramQueryName);
}
};
/**
* Update the histogram chart.
*/
$scope.updateHistogramChart = function() {
var margin = {top:0, right:10, bottom:0, left:0};
var height = $scope.histogramHeight - margin.top - margin.bottom;
var width = $scope.histogramWidth - margin.left - margin.right;
var formatPercent = d3.format('.0%');
// remove any existing charts then create a new chart
d3.select('#date-range-histogram').select('svg').remove();
var svg = d3.select('#date-range-histogram').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// define and configure the x and y scales
var max = d3.max($scope.histogram, function(d) { return d.count; });
var x = d3.scale.ordinal()
.rangeBands([$scope.startYear, $scope.endYear]);
var y = d3.scale.log()
.domain([0,max])
.rangeRound([0,height]);
// define and configure the x and y axes
d3.svg.axis()
.scale(x)
.orient('bottom');
d3.svg.axis()
.scale(y)
.orient('left')
.tickFormat(formatPercent);
// the x domain is the start year to the end year
x.domain([$scope.startYear, $scope.endYear]);
// the y domain is 0 to the largest count value
y.domain([0, max]);
// define tooltip
d3.select('body')
.append('div')
.style('background','white')
.style('border','1px solid #ccc')
.style('position', 'absolute')
.style('z-index', '10')
.style('visibility', 'hidden')
.text('a simple tooltip');
// draw the bar charts
svg.selectAll('.bar')
.data($scope.histogram)
.enter()
.append('rect')
.attr('id',function (d,i) { return 'histogramBar_' + i;})
.attr('class','bar')
.attr('x', function(d, i) { return (i * (width + margin.left + margin.right) / $scope.histogramMaxBins); })
.attr('width', ((width + margin.left + margin.right) / $scope.histogramMaxBins) - 1)
.attr('y', function(d) { return height - (height * d.count / max); })
.attr('height', function(d) { return height * d.count / max; })
.on('click',function(d) {
$scope.endDate = d.end;
$scope.startDate = d.start;
$scope.submit();
});
svg.selectAll('.bar')
.data($scope.histogram)
.exit()
.remove();
};
}]);
/*---------------------------------------------------------------------------*/
/* DocumentSearchResultsController */
/**
* Presents search results for a named query.
* @param $scope
* @param $attrs
* @param $location
* @param $route
* @param $routeParams
* @param $window
* @param SolrSearchService
* @param Utils
*/
angular
.module('ngSolr')
.controller('DocumentSearchResultsController',
['$scope','$attrs','$location','$route','$routeParams','$window','SolrSearchService','Utils',
function ($scope, $attrs, $location, $route, $routeParams, $window, SolrSearchService, Utils) {
// document search results
$scope.documents = [];
// the number of search results to display per page
$scope.documentsPerPage = 10;
// flag for when the controller has submitted a query and is waiting on a
// response
$scope.loading = false;
// the current search result page
$scope.page = 0;
// list of pages in the current navigation set
$scope.pages = [];
// the number of pages in a navigation set
$scope.pagesPerSet = 10;
// the query name
$scope.queryName = SolrSearchService.defaultQueryName;
// url to solr core
$scope.source = undefined;
// zero based document index for first record in the page
$scope.start = 0;
// count of the total number of result pages
$scope.totalPages = 1;
// count of the total number of search results
$scope.totalResults = 0;
// count of the number of search result sets
$scope.totalSets = 1;
// update the browser location on query change
$scope.updateLocationOnChange = true;
// user query
$scope.userquery = '';
///////////////////////////////////////////////////////////////////////////
/**
* A page in a pagination list
* @param Name Page name
* @param Num Page number
*/
function Page(Name,Num) {
this.name = Name;
this.number = Num;
this.isCurrent = false;
}
/**
* Set the results page number.
* @param Start Index of starting document
*/
$scope.handleSetPage = function(Start) {
var query = SolrSearchService.getQuery($scope.queryName);
var oldHash = query.getHash();
query.setOption('start', Start * $scope.documentsPerPage);
if ($scope.updateLocationOnChange) {
var hash = query.getHash();
$location.path($location.path().replace(oldHash, hash));
$window.scrollTo(0, 0);
} else {
$scope.loading = true;
SolrSearchService.updateQuery($scope.queryName);
}
};
/**
* Update the controller state.
*/
$scope.handleUpdate = function() {
// clear current results
$scope.documents = [];
$scope.loading = false;
// get new results
var results = SolrSearchService.getResponse($scope.queryName);
if (results && results.docs) {
$scope.totalResults = results.numFound;
// calculate the total number of pages and sets
$scope.totalPages = Math.ceil($scope.totalResults / $scope.documentsPerPage);
$scope.totalSets = Math.ceil($scope.totalPages / $scope.pagesPerSet);
// add new results
for (var i=0;i<results.docs.length && i<$scope.documentsPerPage;i++) {
// clean up document fields
results.docs[i].fromDate = Utils.formatDate(results.docs[i].fromDate);
results.docs[i].toDate = Utils.formatDate(results.docs[i].toDate);
// add to result list
$scope.documents.push(results.docs[i]);
}
} else {
$scope.documents = [];
$scope.totalResults = 0;
$scope.totalPages = 1;
$scope.totalSets = 1;
}
// update the page index
$scope.updatePageIndex();
};
/**
* Initialize the controller.
*/
$scope.init = function() {
// apply configured attributes
for (var key in $attrs) {
if ($scope.hasOwnProperty(key)) {
if (key === 'documentsPerPage' || key === 'pagesPerSet') {
$scope[key] = parseInt($attrs[key]);
} else if ($attrs[key] === 'true' || $attrs[key] === 'false') {
$scope[key] = $attrs[key] === 'true';
} else {
$scope[key] = $attrs[key];
}
}
}
// handle location change event, update query results
$scope.$on('$routeChangeSuccess', function() {
// if there is a query in the current location
$scope.query = ($routeParams.query || '');
if ($scope.query) {
// reset state
$scope.loading = false;
// get the current query
var query = SolrSearchService.getQueryFromHash($scope.query, $scope.source);
// if there is a data source specified, override the default
if ($scope.source) {
query.solr = $scope.source;
}
query.setOption('rows',$scope.documentsPerPage);
// set the display values to match those in the query
$scope.userquery = query.getUserQuery();
// update query results
SolrSearchService.setQuery($scope.queryName, query);
$scope.loading = true;
SolrSearchService.updateQuery($scope.queryName);
}
});
// handle update events from the search service
$scope.$on($scope.queryName, function () {
$scope.handleUpdate();
});
};
/**
* Update page index for navigation of search results. Pages are presented
* to the user and are one-based, rather than zero-based as the start
* value is.
*/
$scope.updatePageIndex = function() {
var query = SolrSearchService.getQuery($scope.queryName);
$scope.documentsPerPage = (query.getOption('rows') || $scope.documentsPerPage);
$scope.page = (Math.ceil(query.getOption('start') / $scope.documentsPerPage) || 0);
// the default page navigation set
$scope.pages = [];
// determine the current zero based page set
var currentSet = Math.floor($scope.page / $scope.pagesPerSet);
// determine the first and last page in the set
var firstPageInSet = (currentSet * $scope.pagesPerSet) + 1;
var lastPageInSet = firstPageInSet + $scope.pagesPerSet - 1;
if (lastPageInSet > $scope.totalPages) {
lastPageInSet = $scope.totalPages;
}
// link to previous set
if ($scope.totalSets > 1 && currentSet !== 0) {
var previousSet = firstPageInSet - $scope.pagesPerSet - 1;
var prevPage = new Page('«', previousSet);
$scope.pages.push(prevPage);
}
// page links
for (var i=firstPageInSet; i<=lastPageInSet; i++) {
var page = new Page(i, i-1);
if (page.number === $scope.page) {
page.isCurrent = true;
}
$scope.pages.push(page);
}
// link to next set
if ($scope.totalSets>1 && currentSet<$scope.totalSets-1) {
var nextSet = lastPageInSet;
var nextPage = new Page('»', nextSet);
$scope.pages.push(nextPage);
}
};
// initialize the controller
$scope.init();
}]);
/*---------------------------------------------------------------------------*/
/* FacetSelectionController */
/**
* Displays and manages the set of facet constraints on a named query.
* @param $scope Controller scope
* @param $attrs
* @param $location
* @param $route
* @param $routeParams
* @param $window
* @param SolrSearchService Solr search service
*/
angular.module('ngSolr').controller('FacetSelectionController',
['$scope','$attrs','$location','$route','$routeParams','$window','SolrSearchService',
function ($scope, $attrs, $location, $route, $routeParams, $window, SolrSearchService) {
var hash, key, query;
// facets
$scope.items = [];
// URL to Solr core
$scope.source = undefined;
// target query name
$scope.target = SolrSearchService.defaultQueryName;
///////////////////////////////////////////////////////////////////////////
/**
* Remove the facet constraint from the target query.
* @param Index Index of facet in the list
*/
$scope.remove = function(Index) {
query = SolrSearchService.getQuery($scope.target);
var oldHash = query.getHash();
query.removeFacetByIndex(Index);
// change window location
hash = query.getHash();
$location.path($location.path().replace(oldHash, hash));
};
/**
* Update the controller state.
*/
$scope.handleUpdate = function() {
hash = ($routeParams.query || '');
query = SolrSearchService.getQueryFromHash(hash, $scope.source);
if (query) {
$scope.items = query.getFacets();
}
};
/**
* Initialize the controller
*/
$scope.init = function() {
// apply configured attributes
for (key in $attrs) {
if ($scope.hasOwnProperty(key)) {
$scope[key] = $attrs[key];
}
}
// update the list of facets on route change
$scope.$on('$routeChangeSuccess', function() {
$scope.handleUpdate();
});
};
// initialize the controller
$scope.init();
}]);
/* jshint camelcase:false */
/**
* Facet field query controller. Fetches a list of facet values from the search
* index for the specified field. When a facet value is selected by the user, a
* facet constraint is added to the target query, If facets are mutually
* exclusive, the 'hidden' variable is set to true to prevent the user from
* selecting more values. When the facet constraint is removed 'hidden' is set
* back to false.
*
* @param $scope Controller scope
* @param $attrs
* @param $location
* @param $route
* @param $routeParams
* @param $window
* @param SolrSearchService Solr search service
*/
angular
.module('ngSolr')
.controller('FieldFacetController',
['$scope','$attrs','$location','$route','$routeParams','$window','SolrSearchService',
function ($scope, $attrs, $location, $route, $routeParams, $window, SolrSearchService) {
var count, f, facet, facet_fields, facets, facet_query, hash, i, key, name, query, results, s, selected_values, value;
// facet selections are mutually exclusive
$scope.exclusive = true;
// the name of the query used to retrieve the list of facet values
$scope.facetQuery = 'facetQuery';
// the list of facets
$scope.facets = [];
// the name of the field to facet
$scope.field = '';
// the list of facet values
$scope.items = [];
// the max number of items to display in the facet list
$scope.maxItems = 7;
// the name of the search query that we are faceting. we watch this query
// to determine what to present in the facet list
$scope.queryName = SolrSearchService.defaultQueryName;
// a facet value from this set has been selected
$scope.selected = false;
// the url to the solr core
$scope.source = undefined;
///////////////////////////////////////////////////////////////////////////
/**
* Facet result
* @param Value
* @param Score
*/
function FacetResult(Value, Score) {
this.value = Value;
this.score = Score;
}
/**
* Add the selected facet to the facet constraint list.
* @param $event Event
* @param Index Index of user selected facet. This facet will be added to
* the search list.
*/
$scope.add = function($event, Index) {
// create a new facet
query = SolrSearchService.getQuery($scope.queryName);
if (query === undefined) {
query = SolrSearchService.createQuery($scope.source);
}
name = $scope.field;
// ISSUE #27 replace all space characters with * to ensure that Solr matches
// on the space value
value = '(' + $scope.items[Index].value.replace(new RegExp(":", 'g'),' ').split(' ').join('*') + ')';