Algolia - 使用条件搜索以查找字符串数组

时间:2016-01-11 00:41:29

标签: ruby-on-rails-4 mongoid typeahead.js algolia

我正在使用rails和algolia gem以及mongoid数据存储区。

我正在向algolia发送数据Question。 Algolia系统中的一个文档示例是

objectID: 5691e056410213a381000000
text: "what is #cool about your name Mr. John? #name #cool"
asked_to: ["565571704102139759000000", "i7683yiq7r8998778346q686", "kjgusa67g87y8e7qtwe87qwe898989"]
asked_by: "564a9b804102132465000000"
created_at: "2016-01-10T04:38:46.201Z"
card_url: "http://localhost:3000/cards/5691e056410213a381000000"
answerers: []
has_answer: false
requestor_count: 0
status: "active"
popularity_point: 0
created_at_i: 1452400726
_tags: ["cool", "name"]

我想找到符合以下两个条件的所有文件: 1)text包含your name 2)asked_to包含i7683yiq7r8998778346q686

我正在使用Twitter的typeahead javascript库。我的UI实现algolia搜索的javascript如下:

<input class="typeahead ui-widget form-control input-md search-box tt-input" id="typeahead-algolia" placeholder="Search questions" spellcheck="false" type="text" autocomplete="off" dir="auto" style="position: relative; vertical-align: top;">

$(document).on('ready page:load', function () {

  var client = algoliasearch("APPLICATION_ID", "SEARCH_KEY");
  var index = client.initIndex('Question');

  $('#typeahead-algolia').typeahead(
    {
      hint: false,
      highlight: true,
      minLength: 1
    }, 
    {
      source: index.ttAdapter({hitsPerPage: 10}),
      displayKey: 'text'
    }
  ).on('keyup', this, function (event) {
    if (event.keyCode == 13) {
      $('#typeahead-algolia').typeahead('close');
      window.location.href = "/?keyword="+encodeURIComponent($('#typeahead-algolia').val());
    }
  });

  $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
    window.location.href = suggestion.card_url;
  });

});

所以我的问题是:

此代码完美无缺。但是如何在上面的javascript中为asked_to contains i7683yiq7r8998778346q686添加条件以过滤掉结果。

1 个答案:

答案 0 :(得分:4)

您可以在查询的asked_to属性中使用构面过滤器。

首先需要将属性asked_to声明为索引设置中的分面属性,然后通过asked_to:i7683yiq7r8998778346q686查询参数将facetFilters作为构面过滤器传递给查询。 / p>

更改索引设置后,您可以更改源以添加facetFilters参数:

$('#typeahead-algolia').typeahead(
    {
        hint: false,
        highlight: true,
        minLength: 1
    }, 
    {
        source: index.ttAdapter({hitsPerPage: 10, facetFilters: "asked_to:i7683yiq7r8998778346q686"}),
        displayKey: 'text'
    }
).on('keyup', this, function (event) {
    if (event.keyCode == 13) {
        $('#typeahead-algolia').typeahead('close');
        window.location.href = "/?keyword="+encodeURIComponent($('#typeahead-algolia').val());
    }
});