天天看點

Solr與MySQL查詢性能對比

測試環境

本文簡單對比下Solr與MySQL的查詢性能速度。

測試資料量:10407608     Num Docs: 10407608

普通查詢

這裡對MySQL的查詢時間都包含了從MySQL Server擷取資料的時間。

在項目中一個最常用的查詢,查詢某段時間内的資料,SQL查詢擷取資料,30s左右

SELECT * FROM `tf_hotspotdata_copy_test` WHERE collectTime BETWEEN '2014-12-06 00:00:00' AND '2014-12-10 21:31:55';      

對collectTime建立索引後,同樣的查詢,2s,快了很多。

Solr索引資料:

<!--Index Field for HotSpot-->
<field name="CollectTime" type="tdate" indexed="true" stored="true"/>
<field name="IMSI" type="string" indexed="true" stored="true"/>
<field name="IMEI" type="string" indexed="true" stored="true"/>
<field name="DeviceID" type="string" indexed="true" stored="true"/>      

Solr查詢,同樣的條件,72ms

"status": 0,
    "QTime": 72,
    "params": {
      "indent": "true",
      "q": "CollectTime:[2014-12-06T00:00:00.000Z TO 2014-12-10T21:31:55.000Z]",
      "_": "1434617215202",
      "wt": "json"
    }      

好吧,查詢性能提高的不是一點點,用Solrj代碼試試:

SolrQuery params = new SolrQuery();
params.set("q", timeQueryString);
params.set("fq", queryString);
params.set("start", 0); 
params.set("rows", Integer.MAX_VALUE);
params.setFields(retKeys);
QueryResponse response = server.query(params);      

Solrj查詢并擷取結果集,結果集大小為220296,傳回5個字段,時間為12s左右。

為什麼需要這麼長時間?上面的"QTime"隻是根據索引查詢的時間,如果要從solr服務端擷取查詢到的結果集,solr需要讀取stored的字段(磁盤IO),再經過Http傳輸到本地(網絡IO),這兩者比較耗時,特别是磁盤IO。

時間對比:

查詢條件 時間
MySQL(無索引) 30s
MySQL(有索引) 2s
Solrj(select查詢) 12s

如何優化?看看隻擷取ID需要的時間:

SQL查詢隻傳回id,沒有對collectTime建索引,10s左右:

SELECT id FROM `tf_hotspotdata_copy_test` WHERE collectTime BETWEEN '2014-12-06 00:00:00' AND '2014-12-10 21:31:55';      

SQL查詢隻傳回id,同樣的查詢條件,對collectTime建索引,0.337s,很快。

Solrj查詢隻傳回id,7s左右,快了一點。

    id Size: 220296

    Time: 7340

查詢條件(隻擷取ID)
10s
0.337s
7s

繼續優化。。

關于Solrj擷取大量結果集速度慢的一些類似問題:

http://stackoverflow.com/questions/28181821/solr-performance#

http://grokbase.com/t/lucene/solr-user/11aysnde25/query-time-help

http://lucene.472066.n3.nabble.com/Solrj-performance-bottleneck-td2682797.html

這個問題沒有好的解決方式,基本的建議都是做分頁,但是我們需要拿到大量資料做一些比對分析,做分頁沒有意義。

偶然看到一個回答,solr預設的查詢使用的是"/select" request handler,可以用"/export" request handler來export結果集,看看solr對它的說明:

It's possible to export fully sorted result sets using a special rank query parser and response writer  specifically designed to work together to handle scenarios that involve sorting and exporting millions of records. This uses a stream sorting techniquethat begins to send records within milliseconds and continues to stream results until the entire result set has been sorted and exported.

Solr中已經定義了這個requestHandler: 

<requestHandler name="/export" class="solr.SearchHandler">
  <lst name="invariants">
    <str name="rq">{!xport}</str>
    <str name="wt">xsort</str>
    <str name="distrib">false</str>
  </lst>
  <arr name="components">
    <str>query</str>
  </arr>
</requestHandler>      

使用/export需要字段使用docValues建立索引:

<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" docValues="true"/>
<field name="CollectTime" type="tdate" indexed="true" stored="true" docValues="true"/>
<field name="IMSI" type="string" indexed="true" stored="true" docValues="true"/>
<field name="IMEI" type="string" indexed="true" stored="true" docValues="true"/>
<field name="DeviceID" type="string" indexed="true" stored="true" docValues="true"/>      

使用docValues必須要有一個用來Sort的字段,且隻支援下列類型:

Sort fields must be one of the following types: int,float,long,double,string

docValues支援的傳回字段:

Export fields must either be one of the following types: int,float,long,double,string

使用Solrj來查詢并擷取資料:

SolrQuery params = new SolrQuery();
        params.set("q", timeQueryString);
        params.set("fq", queryString);
        params.set("start", 0);
        params.set("rows", Integer.MAX_VALUE);
        params.set("sort", "id asc");
        params.setHighlight(false);
        params.set("qt", "/export");
        params.setFields(retKeys);
        QueryResponse response = server.query(params);      

一個Bug:

org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException: Error from server at http://192.8.125.30:8985/solr/hotspot: Expected mime type application/octet-stream but got application/json. 

Solrj沒法正确解析出結果集,看了下源碼,原因是Solr server傳回的ContentType和Solrj解析時檢查時不一緻,Solrj的BinaryResponseParser這個CONTENT_TYPE是定死的:

public class BinaryResponseParser extends ResponseParser {
    public static final String BINARY_CONTENT_TYPE = "application/octet-stream";      

一時半會也不知道怎麼解決這個Bug,還是自己寫個Http請求并擷取結果吧,用HttpClient寫了個簡單的用戶端請求并解析json擷取資料,測試速度:

String url = "http://192.8.125.30:8985/solr/hotspot/export?q=CollectTime%3A[2014-12-06T00%3A00%3A00.000Z+TO+2014-12-10T21%3A31%3A55.000Z]&sort=id+asc&fl=id&wt=json&indent=true";
    long s = System.currentTimeMillis();
    SolrHttpJsonClient client = new SolrHttpJsonClient();
    SolrQueryResult result = client.getQueryResultByGet(url);
    System.out.println("Size: "+result.getResponse().getNumFound());
    long e = System.currentTimeMillis();
    System.out.println("Time: "+(e-s));      

同樣的查詢條件擷取220296個結果集,時間為2s左右,這樣的查詢擷取資料的效率和MySQL建立索引後的效果差不多,暫時可以接受。

為什麼使用docValues的方式擷取資料速度快?

DocValues是一種按列組織的存儲格式,這種存儲方式降低了随機讀的成本。

傳統的按行存儲是這樣的:

Solr與MySQL查詢性能對比

1和2代表的是docid。顔色代表的是不同的字段。

改成按列存儲是這樣的:

Solr與MySQL查詢性能對比

按列存儲的話會把一個檔案分成多個檔案,每個列一個。對于每個檔案,都是按照docid排序的。這樣一來,隻要知道docid,就可以計算出這個docid在這個檔案裡的偏移量。也就是對于每個docid需要一次随機讀操作。

那麼這種排列是如何讓随機讀更快的呢?秘密在于Lucene底層讀取檔案的方式是基于memory mapped byte buffer的,也就是mmap。這種檔案通路的方式是由作業系統去緩存這個檔案到記憶體裡。這樣在記憶體足夠的情況下,通路檔案就相當于通路記憶體。那麼随機讀操作也就不再是磁盤操作了,而是對記憶體的随機讀。

那麼為什麼按行存儲不能用mmap的方式呢?因為按行存儲的方式一個檔案裡包含了很多列的資料,這個檔案尺寸往往很大,超過了作業系統的檔案緩存的大小。而按列存儲的方式把不同列分成了很多檔案,可以隻緩存用到的那些列,而不讓很少使用的列資料浪費記憶體。

注意Export fields隻支援int,float,long,double,string這幾個類型,如果你的查詢結果隻包含這幾個類型的字段,那采用這種方式查詢并擷取資料,速度要快很多。

下面是Solr使用“/select”和“/export”的速度對比。

Solrj(export查詢)

項目中如果用分頁查詢,就用select方式,如果一次性要擷取大量查詢資料就用export方式,這裡沒有采用MySQL對查詢字段建索引,因為資料量每天還在增加,當達到億級的資料量的時候,索引也不能很好的解決問題,而且項目中還有其他的查詢需求。

分組查詢

我們來看另一個查詢需求,假設要統計每個裝置(deviceID)上資料的分布情況:

用SQL,需要33s:

SELECT deviceID,Count(*) FROM `tf_hotspotdata_copy_test` GROUP BY deviceID;      

同樣的查詢,在對CollectTime建立索引之後,隻要14s了。

看看Solr的Facet查詢,隻要540ms,快的不是一點點。

SolrQuery query = new SolrQuery();
query.set("q", "*:*");
query.setFacet(true);
query.addFacetField("DeviceID");
QueryResponse response = server.query(query);
FacetField idFacetField = response.getFacetField("DeviceID");
List<Count> idCounts = idFacetField.getValues();
for (Count count : idCounts) {
    System.out.println(count.getName()+": "+count.getCount());
}      
查詢條件(統計)
33s
14s
Solrj(Facet查詢) 0.54s

如果我們要查詢某台裝置在某個時間段上按“時”、“周”、“月”、“年”進行資料統計,Solr也是很友善的,比如以下按天統計裝置号為1013上的資料:

String startTime = "2014-12-06 00:00:00";
    String endTime = "2014-12-16 21:31:55";   
    SolrQuery query = new SolrQuery();
    query.set("q", "DeviceID:1013");
    query.setFacet(true);
    Date start = DateFormatHelper.ToSolrSearchDate(DateFormatHelper.StringToDate(startTime));
    Date end = DateFormatHelper.ToSolrSearchDate(DateFormatHelper.StringToDate(endTime));
    query.addDateRangeFacet("CollectTime", start, end, "+1DAY");
    QueryResponse response = server.query(query);

    List<RangeFacet> dateFacetFields = response.getFacetRanges();
    for (RangeFacet facetField : dateFacetFields{
        List<org.apache.solr.client.solrj.response.RangeFacet.Count> dateCounts= facetField.getCounts();
        for (org.apache.solr.client.solrj.response.RangeFacet.Count count : dateCounts) {
            System.out.println(count.getValue()+": "+count.getCount());
        }
    }      

這裡為什麼Solr/Lucene的Facet(聚合)查詢會這麼快呢?

想想Solr/Lucene的索引資料的方式就清楚了:反向索引。對于某個索引字段,該字段下有哪幾個值,對于每個值,對應的文檔集合是建立索引的時候就清楚的,做聚合操作的時候“統計”下就知道結果了。

如果通過docValues建立索引,對于這類Facet查詢會更快,因為這時候索引已經通過字段(列)分割好了,隻需要去對應檔案中查詢統計就行了,如上文所述,通過“記憶體映射”,将該索引檔案映射到記憶體,隻需要在記憶體裡統計下結果就出來了,是以就非常快。

水準拆分表:

由于本系統采集到的大量資料和“時間”有很大關系,一些業務需求根據“時間”來查詢也比較多,可以按“時間”字段進行拆分表,比如按每月一張表來拆分,但是這樣做應用層代碼就需要做更多的事情,一些跨表的查詢也需要更多的工作。綜合考慮了表拆分和使用Solr來做索引查詢的工作量後,還是采用了Solr。

總結:在MySQL的基礎上,配合Lucene、Solr、ElasticSearch等搜尋引擎,可以提高類似全文檢索、分類統計等查詢性能。

參考:

http://wiki.apache.org/solr/

https://lucidworks.com/blog/2013/04/02/fun-with-docvalues-in-solr-4-2/

作者:阿凡盧

出處:http://www.cnblogs.com/luxiaoxun/

本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀