使用 Laravel Eloquent 在 MySQL table 中的所有列中搜索字符串的最优化方法是什么?
What is the most optimised way to search a string across all columns in a MySQL table using Laravel Eloquent?
我们有一个订单 table,其中包含超过 100,000 条记录。场景是从所有 table 的列中搜索一个字符串并找到匹配的结果。我们已准备好此查询,但需要 30 多秒才能完成。
$searchkeyword = "Umair";
$orders = Orders::orderBy("order_number","DESC")
->where(
[
['order_id','=',$searchkeyword],
]
)
->orWhere(
[
['shipping->first_name','LIKE','%'.$searchkeyword.'%'],
]
)
->orWhere(
[
['shipping->last_name','LIKE','%'.$searchkeyword.'%'],
]
)
->orWhere(
[
['billing->email','=',$searchkeyword],
]
)
->orWhere(
[
['billing->phone','=',$searchkeyword],
]
)
->orWhere(
[
['shipping->country','=',$searchkeyword],
]
)
->orWhere(
[
['woo_date_created','LIKE','%'.$searchkeyword.'%']
]
)
->orWhere(
[
['shipment_details->tracking_code','LIKE','%'.$searchkeyword.'%']
]
)
->orWhere([
['shipment_details','LIKE','%'.$searchkeyword.'%']
])
->paginate(200)
->toJson();
能否请您告诉我在 eloquent 中是否有更好更快的方法来执行此类搜索?
无法使用不同的 Laravel 函数来优化您显示的查询。 OR
操作和 LIKE '%word%'
谓词强制查询执行 table-scan.
您可以创建全文索引来提供帮助。在这里阅读:https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
Laravel 似乎没有针对 运行 全文查询的任何特定辅助函数。你只需要使用 whereRaw('MATCH(...columns...) AGAINST (...pattern...)')
。参见 https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible
我们有一个订单 table,其中包含超过 100,000 条记录。场景是从所有 table 的列中搜索一个字符串并找到匹配的结果。我们已准备好此查询,但需要 30 多秒才能完成。
$searchkeyword = "Umair";
$orders = Orders::orderBy("order_number","DESC")
->where(
[
['order_id','=',$searchkeyword],
]
)
->orWhere(
[
['shipping->first_name','LIKE','%'.$searchkeyword.'%'],
]
)
->orWhere(
[
['shipping->last_name','LIKE','%'.$searchkeyword.'%'],
]
)
->orWhere(
[
['billing->email','=',$searchkeyword],
]
)
->orWhere(
[
['billing->phone','=',$searchkeyword],
]
)
->orWhere(
[
['shipping->country','=',$searchkeyword],
]
)
->orWhere(
[
['woo_date_created','LIKE','%'.$searchkeyword.'%']
]
)
->orWhere(
[
['shipment_details->tracking_code','LIKE','%'.$searchkeyword.'%']
]
)
->orWhere([
['shipment_details','LIKE','%'.$searchkeyword.'%']
])
->paginate(200)
->toJson();
能否请您告诉我在 eloquent 中是否有更好更快的方法来执行此类搜索?
无法使用不同的 Laravel 函数来优化您显示的查询。 OR
操作和 LIKE '%word%'
谓词强制查询执行 table-scan.
您可以创建全文索引来提供帮助。在这里阅读:https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
Laravel 似乎没有针对 运行 全文查询的任何特定辅助函数。你只需要使用 whereRaw('MATCH(...columns...) AGAINST (...pattern...)')
。参见 https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible