Solr.js 17.6 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
define(function(require) {
    'use strict';
    var _ = require('underscore');
    var Backbone = require('backbone');

    var Facets = require('solr/model/Facets');
    var Ordering = require('solr/model/Ordering');
    var QueryTextField = require('solr/model/QueryTextField');
    var Util = require('solr/model/Util');

    //var module = require('module');

    var QueryTextFields = Backbone.Model.extend({
        initialize: function(data, options) {
        },
        resetParameters: function(options) {
            _.invoke(this.values(), 'resetParameters', options);
        },
    });
    var Solr = Backbone.Model.extend({
        url: function url() {
            return this.constructor.selectUrl;
        },
        defaults: function defaults() {
            var constructor = this.constructor;
            var formNameMap = {};
            var facets = new Facets(this.constructor.facets, {search: this});
            _.each(facets.values(), function(facet) {
                var formName = facet.get('formName');
                if (formName) {
                    formNameMap[formName] = facet;
                }
            });
            var queryFields = new QueryTextFields();
            _.each(constructor.queryTextFields, function(definition, queryName) {
                var qtf = new QueryTextField({formName: definition.formName, name: queryName, queries: [], fields: definition.fields, multi: !!definition.multi});
                var formName = qtf.get('formName');
                if (formName) {
                    formNameMap[formName] = qtf;
                }
                queryFields.set(queryName, qtf);
            }, this);
            return {
                currentPage: 1,
                pageSize: 10,
                totalCount: 0,
                initializing: true,
                initialized: false,
                query: '',
                formNameMap: formNameMap,
                results: new Backbone.Collection(),
                ordering: new Ordering({items: constructor.orderingItems}, {parse: true}),
                facets: facets,
                queryFields: queryFields,
                options: this._options,
            };
        },
        applyQueryParameters: function() {
            var skipOptions = {skipSearch: true};
            var parts = document.location.href.match(/.*\?(.*)/);
            var facets = this.get('facets');
            facets.resetParameters(skipOptions);
            this.get('queryFields').resetParameters(skipOptions);

            if (parts) {
                var formNameMap = this.get('formNameMap');
                var pagination = {};
                var keyValueParts = parts[1].split('&');
                _.each(keyValueParts, function(keyValuePart, i) {
                    var keyFieldValue = keyValuePart.match(/^([^.]+)(?:\.([^.]+))?=(.*)$/);
                    if (keyFieldValue) {
                        var key = keyFieldValue[1];
                        var field = keyFieldValue[2];
                        var value = keyFieldValue[3];
                        value = value.replace(/(\+|%20)/g, ' ');
                        var impl = formNameMap[key];
                        if (impl) {
                            if (impl instanceof QueryTextField) {
                                impl.set('query', value, skipOptions);
                            } else if ((impl.facetType === 'field' || impl.facetType === 'year') && value) {
                                if (field === 'min') {
                                    impl.set('queryMin', parseInt(value), skipOptions);
                                } else if (field === 'max') {
                                    impl.set('queryMax', parseInt(value), skipOptions);
                                } else if (field === 'items') {
                                    var items = impl.get('items');
                                    var item = items.get(value);
                                    if (!item) {
                                        item = new Facets.Facet.Item({key: value, value: 0});
                                        items.add(item);
                                        item.on('change:checked', function(model, value, options) {
                                            this.trigger('item-change', null, null, options);
                                            impl.trigger('item-change', null, null, options);
                                        }, facets);
                                    }
                                    item.set('checked', true, skipOptions);
                                }
                            }
                        } else if (key === 'p') {
                            pagination['currentPage'] = parseInt(value);
                        } else if (key === 'sz') {
                            pagination['pageSize'] = parseInt(value);
                        }
                    }
                }, this);
                this.set(pagination, skipOptions);
            }
        },
        buildQueryParameters: function() {
            var result = {};
            _.each(this.get('formNameMap'), function(impl, key) {
                if (impl instanceof QueryTextField) {
                    var query = impl.get('query');
                    if (query) {
                        result[key] = query;
                    }
                } else if (impl.facetType === 'field' || impl.facetType === 'year') {
                    var min = impl.get('queryMin');
                    var max = impl.get('queryMax');
                    if (min !== undefined) {
                        result[key + '.min'] = min;
                    }
                    if (max !== undefined) {
                        result[key + '.min'] = max;
                    }
                    var checkedItems = [];
                    impl.get('items').each(function(item) {
                        if (item.get('checked')) {
                            checkedItems.push(item.get('key'));
                        }
                    });
                    if (checkedItems.length) {
                        result[key + '.items'] = checkedItems;
                    }
                }
            });
            result['p'] = this.get('currentPage');
            result['sz'] = this.get('pageSize');
            var serializedQuery = _.map(result, function(value, key) {
                if (_.isArray(value)) {
                    return _.map(value, function(item, index) {
                        return key + '=' + item;
                    }).join('&');
                } else {
                    return key + '=' + value;
                }
            }).join('&');
            this.set('serializedQuery', serializedQuery);
            return this;
        },
        initialize: function(data, options) {
            var solr = this;
            options = (options || {});
            this.set('options', this._options = new Backbone.Model({
                faceting: !!options.faceting,
                highlighting: !!options.highlighting,
                showAll: !!options.showAll,
            }));
            var facets = this.get('facets');
            facets.sync = function sync() {
                return solr.sync.apply(this, arguments);
            };
            this._doSearchImmediately = _.bind(function(options) {
                this.buildQueryParameters();
                this.fetch(_.extend({}, options, {
                    data: this.toJSON(),
                    merge: false,
                    traditional: true,
                }));
            }, this);
            this._doSearch = _.debounce(this._doSearchImmediately, 250);
            this._doSearch = (function(doSearch) {
                return function(options) {
                    var skipSearch = this._skipSearch || (options || {}).skipSearch;
                    if (!skipSearch) {
                        doSearch(options);
                    }
                };
            })(this._doSearch);
            _.each(this.get('queryFields').values(), function(subQueryModel) {
                subQueryModel.on('change:query change:queries', function(model, value, options) {
                    this.trigger('change:queryFields', null, null, options);
                }, this);
            }, this);
            this.on('change:queryFields', function(model, value, options) {
                this.trigger('change:query', null, null, options);
            }, this);
            this.get('options').on('change:faceting change:highlighting', function(model, value, options) {
                this._doSearch(options);
            }, this);
            this.on('change:query', function(model, value, options) {
                // this is silent, which causes the change events to not fire;
                // this is ok, because the next .on will also see the change
                // event on query, and resend the search
                this._doSearch(_.extend({}, options, {resetCurrentPage: true, resetFacets: true, resetOrdering: true}));
            }, this);
            this.on('change:pageSize', function(model, value, options) {
                this._doSearch(_.extend({}, options, {resetCurrentPage: true}));
            }, this);
            this.on('change:currentPage', function(model, value, options) {
                this._doSearch(options);
            }, this);
            facets.on('item-change', function(model, value, options) {
                this._doSearch(_.extend({}, options, {resetCurrentPage: true}));
            }, this);
            this.get('ordering').on('change:value', function(model, value, options) {
                this._doSearch(_.extend({}, options, {resetCurrentPage: true}));
            }, this);
            return Solr.__super__.initialize.apply(this, arguments);

        },
        parse: function parse(data, options) {
            if (options.facetSuggestions) {
                return null;
            }
            var skipOptions = _.extend({}, options, {skipSearch: true});
            if (options.resetCurrentPage) {
                this.set('currentPage', 1, skipOptions);
            }
            if (options.resetFacets) {
                this.get('facets').resetSearch(skipOptions);
            }
            if (options.resetOrdering) {
                this.get('ordering').set('value', this.get('ordering').get('items').at(0).get('value'), skipOptions);
            }
            var facets = this.get('facets');
            if (this.get('options').get('faceting')) {
                facets.applyFacetResults(data, skipOptions);
            } else {
                facets.resetSearch(options);
            }
            var list = [];
            var highlighting = this.get('options').get('highlighting') ? data.highlighting : {};

            var self = this;
            _.each(data.response.docs, function(doc, index) {
                var itemHighlighting = highlighting[doc.id];
                if (!itemHighlighting) {
                    itemHighlighting = {};
                }
                list.push(self.searchParseDoc(doc, index, itemHighlighting));
            });

            return {
                initializing: false,
                initialized: true,
                results: new Backbone.Collection(list),
                facets: facets,
                options: this.get('options'),
                totalCount: data.response.numFound,
                queryTime: (data.responseHeader.QTime / 1000).toFixed(2),
                hasResults: list.length > 0,
            };
        },
        searchParseDoc: function searchParseDoc(doc, index, itemHighlighting) {
            var fieldsToParse = Util.mergeStaticProps(this.constructor, Solr, {}, 'parsedFieldMap');
            var result = {};
            _.each(fieldsToParse, function(value, key) {
                var parsed;
                if (_.isFunction(value)) {
                    parsed = value.call(this, doc, index, itemHighlighting, key);
                } else if (_.isArray(value)) {
                    parsed = [];
                    _.each(value, function(item, i) {
                        var rawValue = doc[item.name];
                        if (rawValue) {
                            var parsedValue = item.parse.call(this, doc, index, itemHighlighting, rawValue, item.name);
                            if (parsedValue) {
                                parsed.push(parsedValue);
                            }
                        }
                    }, this);
                } else {
                    parsed = doc[value];
                }
                result[key] = parsed;
            }, this);
            return result;
        },
        toJSON: function(options) {
            if (!options) {
                options = {};
            }
            var facets = this.get('facets');
            var constructor = this.constructor;
            var result = {
                defType: 'edismax',
                qf: constructor.queryField,
                wt: 'json',
            };
            var ordering = this.get('ordering');
            var sort = ordering.get('value');
            if (options.resetOrdering) {
                sort = ordering.get('items').at(0).get('value');
            }
            var currentPage = this.get('currentPage');
            var pageSize = this.get('pageSize');
            if (options.resetCurrentPage) {
                currentPage = 1;
            }
            result.sort = sort;
            result.rows = pageSize;
            result.start = (currentPage - 1) * pageSize;
            result.fl = Util.mergeStaticSets(constructor, Solr, [], 'returnFields');
            if (this.get('options').get('highlighting')) {
                result.hl = true;
                result['hl.fl'] = ['content', 'title'].concat(constructor.extraHighlightFields);
            }

            if (this.get('options').get('faceting')) {
                var facetFormData = facets.getFacetFormData();
                var fq = facetFormData.fq;
                delete(facetFormData.fq);
                result = _.extend(result, facetFormData);
                if (fq.length) {
                    if (result.fq) {
                        result.fq = result.fq.concat(fq);
                    } else {
                        result.fq = fq;
                    }
                }
            }

            var queryParts = [];
            var queryFields = this.get('queryFields');
            _.each(queryFields.keys(), function(queryName) {
                var subQueryModel = queryFields.get(queryName);
                var fields = subQueryModel.get('fields');
                var queries = subQueryModel.get('queries');
                var query = subQueryModel.get('query');
                if (query) {
                    queries = queries.concat([query]);
                }
                var subQuery = [];
                for (var i = 0; i < fields.length; i++) {
                    var fieldName = fields[i];
                    for (var j = 0; j < queries.length; j++) {
                        // FIXME: quote the query
                        subQuery.push(fieldName + ':\'' + queries[j] + '\'');
                    }
                }
                if (subQuery.length) {
                    queryParts.push(subQuery.join(' OR '));
                }
            }, this);

            var query = queryParts.join(' AND ');
            if (!query) {
                query = '*:*';
                if (!this.get('options').get('showAll') && !result.fq) {
                    result.rows = 0;
                }
            }
            var dateBoostField = constructor.dateBoostField;
            var popularityBoostField = constructor.popularityBoostField;
            if (result.rows !== 0 && (dateBoostField || popularityBoostField)) {
                var boostSum = [];
                if (dateBoostField) {
                    result.dateBoost = 'recip(ms(NOW,' + dateBoostField + '),3.16e-11,1,1)';
                    boostSum.push('$dateBoost');
                }
                if (popularityBoostField) {
                    result.popularityBoost = 'def(' + popularityBoostField + ',0)';
                    boostSum.push('$popularityBoost');
                }
                result.qq = query;
                result.q = '{!boost b=sum(' + boostSum.join(',') + ') v=$qq defType=$defType}';
            } else {
                result.q = query;
            }
            return result;
        },
    }, {
        cleanup: function cleanup(txt) {
            if (txt) {
                txt = txt.replace(/&amp;/g, '&');
                txt = txt.replace(/&#39;/g, '\'');
                txt = txt.replace(/[^a-zA-Z0-9 -\.,:;%<>\/'"|]/g, ' ');
            }
            return txt;
        },
        returnFields: [
            'keywords',
            'last_modified',
            'path',
            'score',
            'title',
        ],
        parsedFieldMap: {
            content: function(doc, index, itemHighlighting) {
                var content = itemHighlighting.content;
                if (content && content.constructor === Array) {
                    content = content.join(' ');
                }
                if (!content) {
                    content = '';
                }
                return this.constructor.cleanup(content);
            },
            keywords: 'keywords',
            lastModified: 'last_modified',
            path: 'url',
            score: 'score',
            title: function(doc, index, itemHighlighting) {
                var title;
                if (itemHighlighting.title) {
                    title = itemHighlighting.title.join(' ');
                } else {
                    title = doc.title[0];
                }
                return this.constructor.cleanup(title);
            },
        },
    });
    Solr.Facets = Facets;
    return Solr;
});