【问题标题】:Best way to filter (search engine) in query在查询中过滤(搜索引擎)的最佳方法
【发布时间】:2020-07-11 15:12:59
【问题描述】:

目前我有一个汽车品牌列表(本田、丰田、宝马、奔驰等)的表(car_brands),我有一个用户可以输入的标题,例如mercedes benz e 230,所以我想要要获取用户的输入,可以通过搜索从 car_brands 表中获取品牌。对我来说最好的方法是什么,我该如何优化它,以便它运行得更快并获得更好的结果。

当前代码是

$user_input = 'mercedes benz e 230';
CarBrand::where('name', 'ilike', '%' . $user_input . '%')->first();

表格结果以此类推..

【问题讨论】:

  • 你有机会看看我的回答吗?

标签: laravel postgresql elasticsearch search eloquent


【解决方案1】:

您可以简单地将您的car_brand 定义为关键字并在之后搜索,过滤car_brand 字段,这将:

  1. 根据您的要求减少仅在特定品牌中搜索的文档,并且要搜索的文档更少意味着搜索速度更快。
  2. 过滤器缓存在 Elasticsearch 中,因此下次再次过滤相同术语示例 mercedes 时,它会从缓存中获取,这与再次过滤数据相比会非常快。

索引定义

{
    "mappings": {
        "properties": {
            "brand": {
                "type": "keyword" --> note
            },
            "title": {
                "type": "text"
            }
        }
    }
}

索引示例文档

{
    "title" : "mercedes benz e 330",
    "brand" : "mercedes"
}

{
    "title" : "fortuner",
    "brand" : "toyota"
}

搜索查询

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "title": "mercedes benz e 330"
                    }
                }
            ],
            "filter": [
                {
                    "term": {
                        "brand": "Mercedes" --> filter `Mercedes` brand and then do search
                    }
                }
            ]
        }
    }
}

结果

 "hits": [
            {
                "_index": "so_query_car",
                "_type": "_doc",
                "_id": "2",
                "_score": 1.2401118,
                "_source": {
                    "title": "mercedes benz e 330",
                    "brand": "mercedes"
                }
            }
        ]

【讨论】:

  • 嗨,但是我如何在 laravel 中编写它?哈哈
  • 另一种想法是汽车品牌是动态的,因此很难过滤,因为我不知道用户会输入的值。他们可能只是输入模型,然后输入品牌
  • @DaljitSingh,1)在您的问题中,您没有提到汽车品牌可以是动态的 2)即使它是动态的,使用客户端,您也可以创建一个适当的查询以包含所有 car_brands 和我知道如何使用 java 客户端而不是 laravel 来做到这一点,如果您理解这个概念并使用 REST API 能够获得预期的结果,那么您可以稍后编写代码。
猜你喜欢
  • 1970-01-01
  • 2012-01-10
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多