Filter Scoring for Tags

I’m trying to figure out how to add filter scoring to tagFilters. I want to be able to display related post based on relative tags but scored. Any ideas?

var els = document.getElementsByClassName("meta");
var arr = [];
var num = 1;
Array.prototype.forEach.call(els, function (el) {
  // Do stuff here
  num = num + 1;
  arr.push('_tags:' + el.innerHTML + '<score=' + num + '>');

});

console.log(arr)

relatedSearch.addWidget(

  instantsearch.widgets.configure({
    facetFilters: [arr],
    hitsPerPage: 3,

  })
);

Hi @nick7,

You can filter on _tags using the ‘filters’ param.

For _tags you do not declare the attribute name ( _tags:Google should be Google )

You do not need an array with the filters param.

So changing your code to create something like this should work:

index.search('harry', {
    "filters": "(Google<score=3> OR Amazon<score=2> OR Facebook<score=1>)"
}

You can find more information about filtering by tags here.

1 Like

Thank you for the response. However, I’m having to pull the tags from the current page. Unless you know of another way, I’m actually having to render the tags assigned via CMS to the page, hide them and then pull from the rendered list to an array, then trying to put all tags in the array in a scorable filter.

Hi @nick7,
Even if you are pulling them from the page you should still be able to create a concatenated string with scores for the syntax @cindy.cullen suggested:

Array.prototype.forEach.call(els, function (el) {
// Do stuff here
num = num + 1;
arr.push(el.innerHTML + ‘<score=’ + num + ‘>’);

});

console.log(arr)

relatedSearch.addWidget(
instantsearch.widgets.configure({
filters: (${arr.join(' OR '}),
hitsPerPage: 3,

})
);

Am I misunderstanding why that wouldn’t work here?

1 Like

@maria.schreiber You are correct. The actual grabbing of the tags IS working. I think the issue is that sumOrFiltersScore doesn’t work with instantsearch.

Can you confirm this? I’m getting the results and consoleing the results of the arr var and it looks like it’s formatting correctly. The issue I’m having is that scoring isn’t effecting the ranking of the search results at all. I’m getting no error codes on the console.

Here’s the full code.

var searchClient = algoliasearch('******', '********');
var index = searchClient.initIndex('onslow_index');
var indexName = 'onslow_index';
var helper = algoliasearchHelper(searchClient, indexName);

const relatedSearch = instantsearch({
  indexName: 'onslow_index',
  searchClient,



});

var els = document.getElementsByClassName("meta");
var arr = [];
var num = els.length;
Array.prototype.forEach.call(els, function (el) {
  // Do stuff here
  num = num - 1;
  arr.push(el.innerHTML + '<score=' + num + '>');

});

console.log(arr)

relatedSearch.addWidget(

  instantsearch.widgets.configure({
    filters: (arr.join(' OR ')),
    hitsPerPage: 3,

  })
);
var hitTemplate = `

        <a href="{{slug}}">
        <img class="grid-item-img" src="{{featured-image}}"/>
        <div class="services-category-div">
          <div class="title-color-id" style="background-color:{{color}};"></div>
          {{category}}
        </div>
        <div class="grid-item-title">{{name}}</div>
        <ul class='list' id="list">
          <li class="tag-link">{{_tags}}</li>
        </ul>
        </a>

`

var newTag = document.getElementById('list');


if ($("#breadcrumb").length) {
  relatedSearch.addWidget(
    instantsearch.widgets.breadcrumb({
      container: '#breadcrumb',
      attributes: [
        'hierarchicalCategories.lvl0',
        'hierarchicalCategories.lvl1',
        'hierarchicalCategories.lvl2',
      ],
    }))
}

relatedSearch.addWidget(

  instantsearch.widgets.hits({
    container: '#related',
    cssClasses: {
      list: 'columns',
      item: 'grid-item small',

    },
    templates: {
      item: hitTemplate,
    },

  })
)

relatedSearch.start();


// ...



// Home Page SUB Featured Content: This query isn't limited to a quanity so we can
// place as many as we need to in this search.








// auto complete for internal search. I believe we could use this across the site. Even on the homepage.

let searchInput = document.getElementById('search-input');
var cursorMoved = false;

searchInput.addEventListener('keyup', e => {
  const returnKey = 13;
  const escKey = 27;
  if (e.which === returnKey && cursorMoved === false) {
    // Submit the form
    window.location.href = '/search-results?query=' + encodeURI(searchInput.value)

  }
});



$('#search-input').on('autocomplete:selected', function (event, suggestion, dataset) {
  cursorMoved = true;
});



autocomplete('#search-input', {
  hint: false,
  debug: false,
  appendTo: '#mainSearch',
  openOnFocus: true,
  routing: true,
  minLength: 0,
  cssClasses: {
    noPrefix: true,
    root: 'alt-search-div internal',

    dropdownMenu: 'search-dropdown alt'
  },
  dropdownMenuContainer: '#root',
}, [{
  source: autocomplete.sources.hits(index, {
    hitsPerPage: 5,
    attributesToSnippet: ["content:25"],
    snippetEllipsisText: " ...",
    highlightPreTag: '<span style="background:yellow; font-weight:bold; text-decoration:underline;">',
    highlightPostTag: '</span>',
  }),
  displayKey: 'name',

  templates: {
    header: `<div id="closeDropdown" class="close_dropdown alt"><div>Press <strong>enter</strong> to select, <strong>↑↓</strong> to navigate, or <strong>esc</strong> to dismiss</div>`,
    footer: `<div id="search-menu" class="description-text left20">Or go to</div>
            <div class="go-to-links"><a href="#" class="btn-2 blue small w-button">Find a Doctor</a><a href="#" class="btn-2 blue small w-button">Patient Portal</a><a href="#" class="btn-2 blue small w-button">Directions</a><a href="#" class="btn-2 blue small w-button">Billing &amp; Insurance</a></div></div>`,
    suggestion: function (suggestion) {
      function content() {
        if (suggestion.content) {
          return suggestion._snippetResult.content.value
        } else {
          return ''
        }
      }
      return `
              <div id="mainHits" class="div-block">
                <a href="${suggestion.slug}" class="dropdown-item w-inline-block"><img src="${suggestion['featured-image']}" alt="" class="dropdown_image">
                  <div class="search-title-snippet">
                    <h4 class="dropdown-name">${suggestion._highlightResult.name.value}</h4>
                    <div class="snippet-text">${content()}</div>
                  </div>
                  <div class="category-text">${suggestion.category}</div>
                </a>
              </div>

              `
    }
  }
}]).on('autocomplete:selected', function (event, suggestion, dataset) {

  window.location.href = suggestion.slug;
})

Another random question and you don’t have to answer anything but yes or no as I know that I would need to start a new thread, but I’m not seeing query rules in the dashboard anymore. Has then been moved to api only?

Hi Nick,
Filter scoring should absolutely work with Instant Search – it’s just another search parameter. To double check, I made the following filter:

{“filters”: “(brand:Apple<score=3> OR brand:HP<score=2> OR brand:LG<score=1>)”}

and applied it here: https://codesandbox.io/s/configure-facet-bu3zo

Results are as I would expect.

Note that filter scoring effects the filter criterion of the ranking formula:

So if there is something “above” that criterion (diff number of typos, a sort-by attribute then the filter scores will not be as clear cut.

If you’re still having trouble identifying why filter scores aren’t working for you, could you e-mail us at support@algolia.com and provide:

  1. Your AppID and index you are working on
  2. Personification access to the account. (By default, we have a limited view of your application.)

Re: Query Rules – this is still a dashboard feature (in fact we’ve released some changes recently to make the UI even more use friendly). However, it is only available on some plans. That said, if you had it on an older plan, they are grandfathered in so you shouldn’t see any change unless you change plans.

Last note: they are accessible on the trial version (we want to give you access to as many features as possible), but if you then move to a free version from the trial, you will lose them.

Hope this helps – feel free to reach out at support@algolia.com if you need further assistance!