简体   繁体   English

elasticsearch-rails如何编写查询查询

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

I am using elasticsearch-rails and elasticsearch-model gem for searching words in my rails app. 我正在使用elasticsearch-rails和elasticsearch-model gem来搜索我的rails应用程序中的单词。

Here is my model article.rb where I want to search to take place: 这是我想要搜索的模型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

Here is my model controller search_controller.rb 这是我的模型控制器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

I am getting search results. 我收到了搜索结果。 But my question is : If I search for "John team". 但我的问题是:如果我搜索“约翰队”。

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

I get multiple records with perfect match 'john team' and some matches related to 'john' or 'team'. 我得到了多个完美匹配'john队'的记录和一些与'john'或'team'相关的比赛。

but I want , if 'john team' is perfectly match in my database the result should only john team.I don't want another records.but if 'john team' is not present I want another results related to 'john' or 'team' both keywords. 但我想,如果'john team'在我的数据库中完全匹配,结果应该只有john team.I不想要其他记录。但是如果'john team'不存在我想要另一个与'john'或'相关的结果团队'两个关键词。

example: 例:

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

But I want 但我想要

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

Try this if you want to match both the words and not any single word 如果您想要匹配单词而不是任何单个单词,请尝试此操作

  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