Skip to content
This repository has been archived by the owner on Apr 12, 2023. It is now read-only.

Commit

Permalink
Merge pull request #1442 from monarch-initiative/search-data-graph
Browse files Browse the repository at this point in the history
[#1386] refactored search ui
  • Loading branch information
jnguyenx authored Apr 14, 2017
2 parents d511425 + 7aeaf75 commit bae9a50
Show file tree
Hide file tree
Showing 4 changed files with 239 additions and 494 deletions.
248 changes: 111 additions & 137 deletions js/search_results.js
Original file line number Diff line number Diff line change
@@ -1,148 +1,122 @@
// searchResults is an array
//console.log(searchResults);


$( document ).ready(function() {
// variable searchTerm is available to use directly here
$('#search').val(searchTerm);

// store filter for each group
var filters = {category: [], taxon_label: []};
var pageNum = 1;

$('.filters').on( 'click', '.search-results-button', function() {
// Show loading indicator
$('#loading-indicator').show();

var $this = $(this);

// Always set pageNum to 1
pageNum = 1;

// get group key
var $buttonGroup = $this.parents('.search-results-button-group');
var filterGroup = $buttonGroup.attr('data-filter-group');

if (filterGroup === 'category') {
if ($this.attr('data-filter') === '') {
filters.category = [];
} else {
filters.category = [$this.attr('data-filter')];
}
}

if (filterGroup === 'taxon_label') {
if ($this.attr('data-filter') === '') {
filters.taxon_label = [];
} else {
filters.taxon_label = [$this.attr('data-filter')];
}
}

// Convert object to JSON string
// E.g. {"category": ["gene"], "taxon_label": ["Danio rerio"]}
// Must use "/" at the beginning of the URL
var url = '/searchfiltering/' + searchTerm + '/' + JSON.stringify(filters) + '/' + pageNum;
//console.log(url);

// fire the new search call and update table
// Separate the ajax request with callbacks
var jqxhr = $.ajax({
url: url,
method: 'GET',
async : true,
dataType : 'json'
});

jqxhr.done(function(data) {
//console.log(data);

// Hide the loading indicator
$('#loading-indicator').hide();

if (typeof(data) !== 'undefined') {
// update the table with this new table content
$('.search-results-rows').html(data.table);

// Update the total count number
$('#totalCount').html(data.count);

if (data.loadMoreBtn === false) {
// Hide the load mroe button
$('#more').hide();
var vueapp = new Vue({
delimiters: ['{[{', '}]}'], // ugly, but otherwise it'll clash with puptent template mechanism
el: '#vue-app',
data: {
facets: [],
user_facets: {},
results: [],
highlight: {},
suggestions: {},
page: 0,
numFound: 0,
numRowsDisplayed: 0
},
methods: {
fetchResults: function () {
//console.log("=== FETCH " + this.page + " " + JSON.stringify(this.user_facets));
var anchor = this;
axios.get('/searchapi/'+searchTerm, {params: this.user_facets})
.then(function (response) {
anchor.numFound = response.data.response.numFound;
anchor.numRowsDisplayed = response.data.response.docs.length;
anchor.results = response.data.response.docs;
anchor.highlight = {};
if(anchor.numFound == 0) {
anchor.fetchSuggestions();
}
// Take the first highilited field and massage it in a more convenient data structure
Object.keys(response.data.highlighting).forEach(function(key) {
var firstKey = Object.keys(response.data.highlighting[key])[0];
anchor.highlight[key] = response.data.highlighting[key][firstKey][0];
});
var facets_fields = response.data.facet_counts.facet_fields;
if(anchor.facets.length == 0) { // for initial visit of the search page
Object.keys(facets_fields).forEach(function(key) {
var json = {};
json[key] = facets_fields[key];
anchor.facets.push(json);
});
} else { // user used facets, just update the numbers
anchor.facets.forEach(function(facet) {
var key = Object.keys(facet)[0];
var filters = facet[key];

// make an inventory of newly fetched facets
var newFacets = {};
facets_fields[key].forEach(function(facets_field) {
newFacets[facets_field[0]] = facets_field[1];
});

// Update the existing filters, with new number if exists, or 0
filters.forEach(function(filter) {
if(newFacets.hasOwnProperty(filter[0])) {
filter[1] = newFacets[filter[0]];
} else {
filter[1] = 0;
}
});

});
}
})
.catch(function (error) {
console.log(error);
});
},
fetchMore: function() {
this.page += 1;
var anchor = this;
//console.log("=== FETCH MORE " + this.page + " " + JSON.stringify(this.user_facets));
var params = jQuery.extend(true, {}, this.user_facetst); // deep copy
params['p'] = this.page;
axios.get('/searchapi/'+searchTerm, {params: params})
.then(function (response) {
anchor.numRowsDisplayed += response.data.response.docs.length;
anchor.results = anchor.results.concat(response.data.response.docs);
Object.keys(response.data.highlighting).forEach(function(key) {
var firstKey = Object.keys(response.data.highlighting[key])[0];
anchor.highlight[key] = response.data.highlighting[key][firstKey][0];
});
})
.catch(function (error) {
console.log(error);
});
},
updateFacets: function(event, category, item) {
if(item == "all") {
delete this.user_facets[category];
} else {
$('#more').show();
this.user_facets[category] = item;
}

// Scroll to top
$(window).scrollTop(0);
this.page = 0;
this.fetchResults();
},
beautifyFacetTitle: function(title) {
// taxon_label => Taxon
// category => Category
var cleanTitle = title.split('_')[0];
return cleanTitle.charAt(0).toUpperCase() + cleanTitle.slice(1);
},
fetchSuggestions: function() {
//console.log("=== FETCH SUGGESTIONS");
var anchor = this;
axios.get('/suggestapi/'+searchTerm)
.then(function (response) {
anchor.suggestions = response.data;
})
.catch(function (error) {
console.log(error);
});
}
});

jqxhr.fail(function () {
console.log('Ajax error!')
});

});


// Load more content
$('#more').click(function(){
// Show loading spinner
$('#more-spinner').show();

// Increase the page number
pageNum++;
//console.log(pageNum);

// Convert object to JSON string
// E.g. {"category": ["gene"], "taxon_label": ["Danio rerio"]}
// Must use "/" at the beginning of the URL
var url = '/searchfiltering/' + searchTerm + '/' + JSON.stringify(filters) + '/' + pageNum;

// fire the new search call and update table
// Separate the ajax request with callbacks
var jqxhr = $.ajax({
url: url,
method: 'GET',
async : true,
dataType : 'json'
});

jqxhr.done(function(data) {
//console.log(data);

// Hide more spinner
$('#more-spinner').hide();

if (typeof(data) !== 'undefined') {
// append new table content
$('.search-results-rows').append(data.table);
}

if (data.loadMoreBtn === false) {
// Hide the load mroe button
$('#more').hide();
} else {
$('#more').show();
}
});

jqxhr.fail(function () {
console.log('Ajax error to fetch more results!')
});
});

}
})

// change is-checked class on buttons
$('.search-results-button-group').each(function(i, buttonGroup) {
var $buttonGroup = $( buttonGroup );
$buttonGroup.on('click', 'li', function() {
// Highlight selected button
$buttonGroup.find('.is-checked').removeClass('is-checked');
$(this).addClass('is-checked');
});
});
// initial call
vueapp.fetchResults();

});

32 changes: 16 additions & 16 deletions lib/monarch/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -1445,11 +1445,11 @@ bbop.monarch.Engine.prototype.getCategories = function(id) {
bbop.monarch.Engine.prototype.resolveIdToType = function(id) {
var engine = this;
var type = false; //Return false if no type is found

if (id.indexOf(":") === -1) {
id = ':' + id;
}

var nodeByID = engine.getGraphNodeByID(id, engine.config.scigraph_data_url);
var graph = new bbop.model.graph();
graph.load_json(nodeByID);
Expand Down Expand Up @@ -2730,7 +2730,7 @@ bbop.monarch.Engine.prototype.annotateText = function(txt, opts) {
r.token.taxon = '';
}
});

// Fetch taxon
var id_list = results.filter(function(i) { return (i.token.categories.indexOf('gene') > -1); })
.map( function(i) { return (i.token.id); });
Expand Down Expand Up @@ -2825,7 +2825,7 @@ bbop.monarch.Engine.prototype.golrHackForSearch = function(golrManager) {
* facets: wanted facets, as array
* rows: number of docs to return
* start: offset of starting row
*
*
* Returns: JSON structure
*/
bbop.monarch.Engine.prototype.search = function(term, filters, facets, rows, start) {
Expand Down Expand Up @@ -2894,20 +2894,20 @@ bbop.monarch.Engine.prototype.search = function(term, filters, facets, rows, sta
* Arguments: term : search term
* category: term category
* limit: number of results to return
*
*
* Returns: JSON structure
*/
bbop.monarch.Engine.prototype.autocomplete = function(term, category, limit) {
var engine = this;

// TODO return only fields of interest
var searchGolrManager = engine.initializeGolrManager("monarch_search", this.config.search_url);

searchGolrManager.include_highlighting(true);

searchGolrManager.set_query(term);

// TODO DELETE THIS WHEN #XXX is done
// TODO DELETE THIS WHEN #1387 is done
engine.golrHackForSearch(searchGolrManager);
// END OF DELETE

Expand Down Expand Up @@ -4107,7 +4107,7 @@ bbop.monarch.Engine.prototype.querySciGraphDynamicServices = function(path,param
*
* Below are a number of functions, partially tested, that are developed
* to work with scigraph and solr/golr services. Unit tests in apitests.js
*
*
*/
bbop.monarch.Engine.prototype.initializeGolrManager = function(personality, golrServer) {
var golr_response = require('bbop-response-golr');
Expand Down Expand Up @@ -4167,10 +4167,10 @@ bbop.monarch.Engine.prototype.fetchAssociations = function(filters, limit, perso
}

golrManager.lite(true); //only return fields in results in the conf file

golrManager.set_results_count(limit);
golrManager.set_facet_limit(-1); //unlimited

// Add AND filters
if (filters != null && filters instanceof Array && filters.length > 0){
filters.forEach( function (val) {
Expand All @@ -4181,7 +4181,7 @@ bbop.monarch.Engine.prototype.fetchAssociations = function(filters, limit, perso
}
});
}

// Add OR filters
if (orFilter != null && orFilter instanceof Array && orFilter.length > 0){
var orFilters = orFilter.map( function (val) {
Expand All @@ -4190,9 +4190,9 @@ bbop.monarch.Engine.prototype.fetchAssociations = function(filters, limit, perso
var orFilterString = orFilters.join(" OR ");
golrManager.add_query_filter_as_string(orFilterString);
}

//Add OR filters

if (logFetchTimes) {
var timeDelta = Date.now();
this.log("FETCHING: " + "GET" + " " + golrManager.get_state_url());
Expand All @@ -4207,7 +4207,7 @@ bbop.monarch.Engine.prototype.fetchAssociations = function(filters, limit, perso
// TODO remove this
bbop.monarch.Engine.prototype.fetchSolrDocuments = function (query, filters, personality, limit) {
var engine = this;

var golrManager = engine.initializeGolrManager(personality);

golrManager.set_query(query);
Expand All @@ -4221,12 +4221,12 @@ bbop.monarch.Engine.prototype.fetchSolrDocuments = function (query, filters, per
if (typeof limit !== 'undefined'){
golrManager.set_results_count(limit);
}

if (logFetchTimes) {
var timeDelta = Date.now();
this.log("FETCHING: " + "GET" + " " + golrManager.get_state_url());
}

return golrManager.search();
};

Expand Down
Loading

0 comments on commit bae9a50

Please sign in to comment.