设为首页 收藏本站
查看: 691|回复: 0

[经验分享] python solr客户端

[复制链接]

尚未签到

发表于 2016-12-15 08:29:44 | 显示全部楼层 |阅读模式
  原文:http://blog.chenlb.com/2010/03/use-solr-python-client.html
  最近开始慢慢使用 python 了,用 python 处理小事情还是很方便的(比 java 开发效率高)。拿 python 来做 solr 索引也方便。
  官方有相关的 solr python 客户端
,我简单对比了下选择 solrpy
,理由是使用说明详细一点、功能丰富一点、项目感得比较活。
  tips:从 solr 1.3 开始官方已经不在维护 solr 客户端了。
  安装 solrpy:



  • easy_install solrpy  


  •   

  • # 或者用源码安装
      


  •   

  • python setup.py install
      


  安装 easy_install 我就不写了,使用 python 的人都知道。
  查询示例:

    import solr  
s = solr.SolrConnection('http://127.0.0.1:8080/solr')  
result = s.query("*:*", rows=5)  
for r in result:  
print r['id'], r['title']  
   方便的查询方法。返回的结果用字典类型(如果 object 类型就更方便了)。
  官方的示例:

  import solr   
# create a connection to a solr server  
s = solr.SolrConnection('http://example.org:8083/solr')   
# add a document to the index  
s.add(id=1, title='Lucene in Action', author=['Erik Hatcher', 'Otis Gospodnetić'])  
s.commit()   
# do a search  
response = s.query('title:lucene')  
for hit in response.results:  
print hit['title']  
  方法有 query (q, fields=None, highlight=None, score=True, sort=None,
**params) 、add_many(list) 、delete(id)
、delete_query(query)、commit(wait_flush=True,
wait_searcher=True)、optimize(wait_flush=True, wait_searcher=True)  
等方法,还有一个方便的就是翻页 next_batch()。
  更多使用请看:http://code.google.com/p/solrpy/source/browse/trunk/solr/core.py
的注释。
  越来越喜欢 python 了,python 周边工具/库还是比较多,很容易找到对应的库。当然 solrj 也方便。
  更多:http://wiki.apache.org/solr/SolPython
  A simple Solr client for python.



Features

--------

 * Supports Solr 1.2+

 * Supports http/https and SSL client-side certificates

 * Uses persistent HTTP connections by default

 * Properly converts to/from Solr data types, including datetime objects

 * Supports both querying and update commands (add, delete)

 * Requires Python 2.3+



Connections

-----------

`SolrConnection` can be passed in the following parameters.

Only `url` is required,.


    url -- URI pointing to the Solr instance. Examples:


        http://localhost:8080/solr

        https://solr-server/solr


        Your python install must be compiled with SSL support for the

        https:// schemes to work. (Most pre-packaged pythons are.)


    persistent -- Keep a persistent HTTP connection open.

        Defaults to true.


    timeout -- Timeout, in seconds, for the server to response.

        By default, use the python default timeout (of none?)

        NOTE: This changes the python-wide timeout.


    ssl_key, ssl_cert -- If using client-side key files for

        SSL authentication,  these should be, respectively,

        your PEM key file and certificate file

       

    http_user, http_pass -- If given, include HTTP Basic authentication

        in all request headers.


Once created, a connection object has the following public methods:


    query(q, fields=None, highlight=None,

          score=True, sort=None, **params)


            q -- the query string.


            fields -- optional list of fields to include. It can be either

                a string in the format that Solr expects ('id,f1,f2'), or

                a python list/tuple of field names.   Defaults to returning

                all fields. ("*")


            score -- boolean indicating whether "score" should be included

                in the field list.  Note that if you explicitly list

                "score" in your fields value, then this parameter is

                effectively ignored.  Defaults to true.


            highlight -- indicates whether highlighting should be included.

                `highlight` can either be `False`, indicating "No" (the

                default),  `True`, incidating to highlight any fields

                included in "fields", or a list of field names.


            sort -- list of fields to sort by.


            Any parameters available to Solr 'select' calls can also be

            passed in as named parameters (e.g., fq='...', rows=20, etc).


            Many Solr parameters are in a dotted notation (e.g.,

            `hl.simple.post`).  For such parameters, replace the dots with

            underscores when calling this method. (e.g.,

            hl_simple_post='</pre'>)


            Returns a Response object


    add(**params)


            Add a document.  Pass in all document fields as

            keyword parameters:


                add(id='foo', notes='bar')


            You must "commit" for the addition to be saved.


    add_many(lst)


            Add a series of documents at once.  Pass in a list of

            dictionaries, where each dictionary is a mapping of document

            fields:


                add_many( [ {'id': 'foo1', 'notes': 'foo'},

                            {'id': 'foo2', 'notes': 'w00t'} ] )


            You must "commit" for the addition to be saved.


    delete(id)


            Delete a document by id.


            You must "commit" for the deletion to be saved.


    delete_many(lst)


            Delete a series of documents.  Pass in a list of ids.


            You must "commit" for the deletion to be saved.


    delete_query(query)


            Delete any documents returned by issuing a query.


            You must "commit" for the deletion to be saved.



    commit(wait_flush=True, wait_searcher=True)


            Issue a commit command.


    optimize(wait_flush=True, wait_searcher=True)


            Issue an optimize command.


    raw_query(**params)


            Send a query command (unprocessed by this library) to

            the Solr server. The resulting text is returned un-parsed.


                raw_query(q='id:1', wt='python', indent='on')


            Many Solr parameters are in a dotted notation (e.g.,

            `hl.simple.post`).  For such parameters, replace the dots with

            underscores when calling this method. (e.g.,

            hl_simple_post='</pre'>)


    close()

            Close the underlying HTTP(S) connection.



Query Responses

---------------


    Calls to connection.query() return a Response object.


    Response objects always have the following properties:


        results -- A list of matching documents. Each document will be a

            dict of field values.


        results.start -- An integer indicating the starting # of documents


        results.numFound -- An integer indicating the total # of matches.


        results.maxScore -- An integer indicating the maximum score assigned

                            to a document. Takes into account all of documents

                            found by the query, not only the current batch.


        header -- A dict containing any responseHeaders.  Usually:


            header['params'] -- dictionary of original parameters used to

                        create this response set.


            header['QTime'] -- time spent on the query


            header['status'] -- status code.


            See Solr documentation for other/typical return values.

            This may be settable at the Solr-level in your config files.



        next_batch() -- If only a partial set of matches were returned

            (by default, 10 documents at a time), then calling

            .next_batch() will return a new Response object containing

            the next set of matching documents. Returns None if no

            more matches.


            This works by re-issuing the same query to the backend server,

            with a new 'start' value.


        previous_batch() -- Same as next_batch, but return the previous

            set of matches.  Returns None if this is the first batch.


    Response objects also support __len__ and iteration. So, the following

    shortcuts work:


        responses = connection.query('q=foo')

        print len(responses)

        for document in responses:

            print document['id'], document['score']



    If you pass in `highlight` to the SolrConnection.query call,

    then the response object will also have a "highlighting" property,

    which will be a dictionary.



Quick examples on use:

----------------------


Example showing basic connection/transactions


    >>> from solr import *

    >>> c = SolrConnection('http://localhost:8983/solr')

    >>> c.add(id='500', name='python test doc', inStock=True)

    >>> c.delete('123')

    >>> c.commit()



Examples showing the search wrapper


    >>> response = c.query('test', rows=20)

    >>> print response.results.start

     0

    >>> for match in response:

    ...     print match['id'],

      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

    >>> response = response.next_batch()

    >>> print response.results.start

     20


Enter a raw query, without processing the returned HTML contents.


    >>> print c.raw_query(q='id:[* TO *]', wt='python', rows='10')

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-314426-1-1.html 上篇帖子: Solr 空间查询 下篇帖子: Solr 使用入门介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表