SolrをPHPで使う(検索編)
前回の記事でSolrをPHPから使う準備ができました。
今回はPHPで Solr の検索を実行する方法です。
検索結果のオブジェクトは以下のような構造になっています。
SolrObject Object ( [responseHeader] => SolrObject Object ( [zkConnected] => 1 [status] => 0 [QTime] => 0 [params] => SolrObject Object ( [q] => *:* [indent] => on [start] => 0 [rows] => 2 [version] => 2.2 [wt] => xml ) ) [response] => SolrObject Object ( [numFound] => 52 [start] => 0 [docs] => Array ( [0] => SolrDocument Object ( [_hashtable_index:SolrDocument:private] => 24804 ) [1] => SolrDocument Object ( [_hashtable_index:SolrDocument:private] => 5340 ) ) ) )
docs という配列の要素である SolrDocument オブジェクトは SolrDocumentField オブジェクトを複数含んでいます。SolrDocument 内のすべての SolrDocumentField をたどるために current() や next() などのメソッドを利用します。
SolrObject ベースの検索結果は意外と扱いづらいので、JSON で扱えるようにしてみます。
SolrClient 作成時のオプションとして wt=json を追加しています。
getRawResponse() の応答は以下の通りです。
{ "responseHeader":{ "zkConnected":true, "status":0, "QTime":0, "params":{ "q":"*:*", "indent":"on", "start":"0", "rows":"2", "version":"2.2", "wt":"json"}}, "response":{"numFound":52,"start":0,"numFoundExact":true,"docs":[ { "id":"0553573403", "cat":["book"], "name":"A Game of Thrones", "price":7.99, "price_c":"7.99,USD", "inStock":true, "author":"George R.R. Martin", "author_s":"George R.R. Martin", "series_t":"A Song of Ice and Fire", "sequence_i":1, "genre_s":"fantasy", "_version_":1730974266238697472, "price_c____l_ns":799}, { "id":"0553579908", "cat":["book"], "name":"A Clash of Kings", "price":7.99, "price_c":"7.99,USD", "inStock":true, "author":"George R.R. Martin", "author_s":"George R.R. Martin", "series_t":"A Song of Ice and Fire", "sequence_i":2, "genre_s":"fantasy", "_version_":1730974266279591936, "price_c____l_ns":799}] }}
これを json_decode() することで、通常の PHP 配列として扱うことができます。
Array ( [responseHeader] => Array ( [zkConnected] => 1 [status] => 0 [QTime] => 0 [params] => Array ( [q] => *:* [indent] => on [start] => 0 [rows] => 2 [version] => 2.2 [wt] => json ) ) [response] => Array ( [numFound] => 52 [start] => 0 [numFoundExact] => 1 [docs] => Array ( [0] => Array ( [id] => 0553573403 [cat] => Array ( [0] => book ) [name] => A Game of Thrones [price] => 7.99 [price_c] => 7.99,USD [inStock] => 1 [author] => George R.R. Martin [author_s] => George R.R. Martin [series_t] => A Song of Ice and Fire [sequence_i] => 1 [genre_s] => fantasy [_version_] => 1730974266238697472 [price_c____l_ns] => 799 ) [1] => Array ( [id] => 0553579908 [cat] => Array ( [0] => book ) [name] => A Clash of Kings [price] => 7.99 [price_c] => 7.99,USD [inStock] => 1 [author] => George R.R. Martin [author_s] => George R.R. Martin [series_t] => A Song of Ice and Fire [sequence_i] => 2 [genre_s] => fantasy [_version_] => 1730974266279591936 [price_c____l_ns] => 799 ) ) ) )