【问题标题】:elasticsearch-rails how to write query for searchelasticsearch-rails 如何编写搜索查询
【发布时间】:2017-02-06 12:40:48
【问题描述】:

我正在使用 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

我正在获取搜索结果。 但我的问题是: 如果我搜索“John team”。

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

我获得了多个完美匹配“john team”的记录以及一些与“john”或“team”相关的匹配项。

但我想要,如果“john team”在我的数据库中完全匹配,结果应该只有 john team。我不想要其他记录。但是如果“john team”不存在,我想要另一个与“john”相关的结果' 或 'team' 两个关键字。

示例:

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

但我想要

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

【问题讨论】:

    标签: ruby-on-rails elasticsearch-rails


    【解决方案1】:

    如果你想同时匹配两个单词而不是任何一个单词,试试这个

      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
    

    【讨论】:

    • 嗨,谢谢你的回复。我试过这个我得到了
    • database_timezone 选项必须是 :utc 或 :local Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {"error":{"root_cause":[{"type": "query_parsing_exception","re​​ason":"没有为 multi_match 查询指定字段","index":"talents","line":1,"col":94}],"type":"search_phase_execution_exception","re​​ason" :"所有分片失败","phase":"query_fetch","grouped":true,"failed_shards":[{"shard":0,"index":"talents","node":"M_Xg7KxeQNiYaB8XPphFrQ"," reason":{"type":"query_parsing_exception","re​​ason":"没有为 multi_match 查询指定字段","index":"talents","line":1,"col":94}}]},"状态“:400}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多