使用or和运算符在ElasticSearch上搜索多个字段

时间:2013-10-28 10:09:36

标签: mysql elasticsearch

我需要来自MySql的elasticsearch查询等价物。我的SQL查询:

SELECT DISTINCT t.product_id AS id 
FROM tbl_sup_price t 
    INNER JOIN product a ON t.product_id = a.product_id 
    INNER JOIN a_product_to_category a2 ON a.product_id = a2.product_id 
    INNER JOIN a_category_description a3 ON a2.category_id = a3.category_id 
    INNER JOIN tbl_sup t2 ON t.sup_id = t2.id AND (t2.status = 1) 
WHERE ((t.quantity - t.reserved) > 0 AND t.is_active = 1) 
    AND (a.model_name LIKE '%word1%' OR t.name LIKE '%word1%') 
    AND (a.model_name LIKE '%word2%' OR t.name LIKE '%word2%') 
ORDER BY a.price ASC

我尝试了很多选项,但没有找到我想要的东西,有人能告诉我如何解决这个问题吗?

例如:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "and": [
          {
            "or": [
              {
                "fuzzy": {
                  "model_name": "nokian"
                }
              },
              {
                "fuzzy": {
                  "product_name": "nokian"
                }
              }
            ]
          },
          {
            "or": [
              {
                "text": {
                  "model_name": "195"
                }
              },
              {
                "text": {
                  "product_name": "195"
                }
              }
            ]
          }
        ]
      }
    }
  }
}

但是,如果我运行此查询,我有错误:

Parse Failure [Failed to parse source [{"query":{"filtered":{"query":{"match_all":{}},"filter":{"and":[{"or":[{"fuzzy":{"model_name":"nokian"}},{"fuzzy":{"product_name":"nokian"}}]},{"or":[{"text":{"model_name":"195"}},{"text":{"product_name":"195"}}]}]}}}}]]]; nested: QueryParsingException[[index] No filter registered for [fuzzy]]; }]

如果单词是数字 - 搜索类型必须是文本,否则 - 模糊

1 个答案:

答案 0 :(得分:1)

我解决了这个问题。在ElasticSearch中,有一个很棒的功能function_score

{
  "query": {
    "bool": {
      "must": [
        {
          "function_score": {
            "query": {
              "bool": {
                "should": [
                  {
                    "fuzzy": {
                      "model_name": "word1"
                    }
                  },
                  {
                    "fuzzy": {
                      "product_name": "word1"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "function_score": {
            "query": {
              "bool": {
                "should": [
                  {
                    "fuzzy": {
                      "model_name": "word2"
                    }
                  },
                  {
                    "fuzzy": {
                      "product_name": "word2"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}