簡體   English   中英

elasticsearch-rails如何編寫查詢查詢

[英]elasticsearch-rails how to write query for search

我正在使用elasticsearch-rails和elasticsearch-model gem來搜索我的rails應用程序中的單詞。

這是我想要搜索的模型article.rb:

require 'elasticsearch/model'

class Article < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fuzziness: 2,
            fields: ['title^10', 'text']
          }
        },
        highlight: {
          pre_tags: ['<em>'],
          post_tags: ['</em>'],
          fields: {
            title: {},

          }
        }
      }
    )
  end
end

這是我的模型控制器search_controller.rb

class SearchController < ApplicationController

  def search
    if params[:q].nil?
      @articles = []
    else
      @articles = Article.search params[:q]
      logger.info "LocationController.add_locations called with params: #{@articles.records.each_with_hit { |record, hit| puts "* #{record.title}: #{hit._score}" }}"
    end
  end
end

我收到了搜索結果。 但我的問題是:如果我搜索“約翰隊”。

Articles.search('John team').records.records

我得到了多個完美匹配'john隊'的記錄和一些與'john'或'team'相關的比賽。

但我想,如果'john team'在我的數據庫中完全匹配,結果應該只有john team.I不想要其他記錄。但是如果'john team'不存在我想要另一個與'john'或'相關的結果團隊'兩個關鍵詞。

例:

Article.search('John team').records.records
responce: ('john team', 'team joy', 'John cena')

但我想要

   Article.search('John team').records.records
    responce: ('john team')

如果您想要匹配單詞而不是任何單個單詞,請嘗試此操作

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query:{ match: {content: {query: query, operator: "and" }}},
            fuzziness: 2,
            fields: ['title^10', 'text']
          }
        },
        highlight: {
          pre_tags: ['<em>'],
          post_tags: ['</em>'],
          fields: {
            title: {},

          }
        }
      }
    )
  end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM