2017-07-28 44 views
3

不太清楚如何解決這個問題,如果這甚至是我的查詢或數據庫的問題,所以在這裏。有3個表格,產品,關係和標籤。去這些類別之間Laravel試圖查詢多個表格

'products' (
    'ID' bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
    'user_id' bigint(20) unsigned NOT NULL, 
    'name' varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'primary_image' bigint(20) DEFAULT NULL, 
    'description' longtext COLLATE utf8mb4_unicode_ci, 
    'price' float DEFAULT NULL, 
    'sale_price' float DEFAULT NULL, 
    'currency' varchar(25) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'primary_color' varchar(7) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'secondary_color' varchar(7) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'status' varchar(15) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'quantity' bigint(20) DEFAULT NULL, 
    'origin' varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'type' varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'size' varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'processing_time' varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    'date_added' int(11) DEFAULT NULL, 
    PRIMARY KEY ('ID') 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 

'relations' (
    'ID' bigint(20) unsigned NOT NULL, 
    'relation_id' bigint(20) unsigned NOT NULL, 
    'type' varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL, 
    'options' text COLLATE utf8mb4_unicode_ci, 
    KEY 'ID' ('ID'), 
    KEY 'relation_id' ('relation_id') 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 

'tags' (
    'ID' bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
    'name' varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL, 
    'slug' varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL, 
    PRIMARY KEY ('ID') 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 

關係如下:

  • products.ID = relations.ID
  • relations.relation_id = tags.ID

有50K的產品,250K關係和25k標籤添加到數據庫進行測試。

我正在構建一個在產品名稱,描述和標籤內進行搜索的查詢。

執行這個查詢:

Product::select('ID', 'name')->where('name', 'like', '%'.$search_query.'%')->orWhere('description', 'like', '%'.$search_query.'%')->orWhereHas('relations', function($query) use($search_query) { 
    $query->where('type', 'tags')->whereHas('tags', function($query) use($search_query) { 
     $query->where('name', 'like', '%'.$search_query.'%'); 
    }); 
})->paginate(25); 
  • 這個查詢需要大約0.8秒查找數據,如果我查詢特定的標籤,它需要只要1.8秒
  • 我建立了一個類似的與連接查詢,並花了更長的時間,所以我現在留在上面的查詢。

你們有沒有想法我可能做錯了什麼?這裏的主要問題是查詢執行時間。

+1

如果你有興趣,Laravel偵察https://laravel.com/docs/5.4/scout有一個MySQL驅動https://github.com/damiantw/laravel-scout -mysql驅動程序。除了需要很長時間以外,您的查詢有什麼問題嗎? – Jeff

+0

謝謝,我會考察童軍。不是我意識到的,只是純粹的執行時間,因爲我們期待更多的數據,所以我擔心執行時間將會成爲問題。 – John

回答

0

沒有辦法來優化我所知道的這個查詢。如果你有'LIKE', searchquery.'%'(沒有前導%),你可以索引文本列來提高速度。如果兩端都需要使用通配符的功能,則必須使用全文索引搜索提供程序。 Algolia https://www.algolia.com/是我所知道的,Laravel Scout是爲了與他們的搜索合作而創建的。這other question也參考http://sphinxsearch.com/http://lucene.apache.org/core/雖然我不知道他們做什麼。

編輯:也https://www.elastic.co/products/elasticsearch