`
san_yun
  • 浏览: 2639197 次
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

python solr客户端

 
阅读更多

原文: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:

  1. easy_install solrpy  
  2.   
  3. # 或者用源码安装   
  4.   
  5. 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')

分享到:
评论

相关推荐

    pysolr:Pysolr-Python Solr客户端

    pysolr是的轻量级Python客户端。 它提供了一个查询服务器的接口,并根据查询返回结果。 地位 特征 基本操作,例如选择,更新和删除。 索引优化。 支持(如果在Solr中设置)。 (如果在Solr中设置)。 超时支持...

    Solr部署及开发

    例如,你可以使用Python的Solr客户端库(如`solrpy`或`pysolr`)来编写索引和查询的脚本。同时,Solr还支持SolrJ,这是一个专门的Java客户端API,方便Java开发者进行集成。 为了优化搜索体验,Solr提供了多种查询...

    Solr调研总结共48页.pdf.zip

    - **Solr客户端库**:如 pysolr,用于Python应用程序与Solr之间的交互,支持增删改查操作。 - **批量导入数据**:使用Solr的DataImportHandler或Python脚本批量导入结构化数据。 5. **Solr与C语言、STM32及小程序...

    solr简单应用操作的代码部分

    Solr提供了客户端库,简化了这个过程。以Java为例,我们可以使用SolrJ库来发送请求和处理响应: ```java SolrClient client = new HttpSolrClient("http://localhost:8983/solr/simple"); SolrQuery query = new ...

    solrcraft:Solr的Python库

    Solrcraft是针对Python开发者的Solr客户端库,它简化了Python程序与Solr服务器之间的通信过程。使用Solrcraft,开发者可以方便地进行索引构建、查询执行、文档添加、更新和删除等操作。该库的主要特性包括: 1. **...

    solr in action配套代码和数据

    3. **Java客户端代码**:可能是Java API的示例,展示了如何与Solr服务器进行交互,如添加、更新和删除文档,执行查询,或者处理结果。 4. **脚本**:可能包括用于自动化任务的shell脚本或Python脚本,如批量导入...

    solr 企业搜索引擎教程

    API模块提供了客户端访问接口等。 #### 5. Solr 的版本说明 - **1.3版本**:引入了数据导入功能。 - **1.4版本**:进一步增强了数据导入功能,并优化了性能。 #### 6. Solr 的分布式与复制架构 - **分布式架构**...

    solr-8.6.0.zip

    - 客户端库(如 Java、Python、Ruby 等)也可能会进行相应的更新,以支持新版本的功能。 7. **配置与索引优化**: - 用户可以利用新的配置选项来优化索引结构,比如使用近实时搜索(NRT)、位图压缩和其他高级...

    solr5.5.5安装

    你可以使用各种编程语言的客户端库与Solr交互,如Java、Python、PHP等。 **七、监控与优化** Solr提供了一个内置的监控界面,可以通过`http://localhost:8983/solr/admin`访问。这里可以查看索引状态、查询性能、...

    solr示例(含代码,jar包,文档)

    - **示例代码**:可能包含Java或Python等语言的示例,展示了如何使用Solr API进行索引创建、文档添加、查询操作等。 - **jar包**:Solr的库文件,包括solr-jar和相关依赖,这些jar包是运行和开发Solr应用的基础。 ...

    在tomcat环境下搭建solr和mmseg4j搜索引擎

    Solr提供了一个RESTful API,允许使用任何能够发送HTTP请求的工具(如curl或Python)进行索引数据、查询和管理操作。例如,使用`curl`向Solr发送JSON数据进行索引: ```bash curl -X POST -H 'Content-Type:...

    Apache Solr 3 Enterprise Search Server

    - **服务器端集成**:Solr可以轻松地与其他服务器端技术集成,如Java、Python等。 - **客户端JavaScript集成**:通过RESTful API与前端JavaScript框架无缝对接。 - **框架集成**:支持与Drupal等流行CMS系统的集成,...

    文章-Python一年一度秀代码时间罒ω罒-资源附属包

    开发者可能利用了Python的文本处理库,如jieba(用于中文分词)和pysolr(用于Solr搜索引擎的Python客户端),以快速高效地搜索诗词。此外,为了提升用户体验,可能还涉及到了用户交互界面设计,比如使用tkinter或...

    solr的增删改查和高亮以及分组

    Solr是Apache Lucene项目的一个子项目,是一个高性能、全文本搜索服务器,...在使用Solrtest压缩包文件进行实践时,可以通过编写相应的Java或Python客户端代码来实现上述功能,从而更好地理解和掌握Solr的工作原理。

    搜索引擎-使用javascript+python开发的分布式百度网盘搜索引擎-优质项目分享.zip

    同时,Python还可能用于构建索引,例如使用Elasticsearch或Solr等搜索引擎库。此外,Python的多线程或多进程特性使其适合处理分布式任务,可以有效提高数据抓取和处理的速度。 **分布式**是该项目的核心部分,它...

    sorl 安装包

    在Python代码中,你可以使用`sorl.client.Solr`类来创建一个客户端实例,如下所示: ```python from pysolr import Solr solr = Solr('http://localhost:8983/solr/your_core_name') ``` 这里,'...

    Python的BBS问答社区程序.zip

    如果BBS社区需要提供API供其他应用或移动客户端使用,Python的Flask或Django框架都有很好的支持。它们能够帮助我们构建遵循REST原则的API,实现数据的增删查改。 8. 前端技术: 虽然这里的重点是Python后端,但...

    PyPI 官网下载 | pysolr-tornado-4.0.0a2.tar.gz

    pysolr是Solr的Python客户端,它为Solr提供了一个简洁、易用的接口。Solr是Apache软件基金会的一个开源项目,是一款功能强大的全文搜索引擎,广泛用于构建高性能的搜索应用。pysolr库使得Python开发者能够轻松地与...

    Python库 | haystack-client-0.2.4.tar.gz

    Haystack是一个用于构建、测试和维护全文搜索应用的Python库,它抽象了各种搜索引擎后端,如Elasticsearch、Solr、Whoosh等,使得开发者可以无需关心底层实现,专注于业务逻辑。`haystack-client`作为其客户端,...

    Tutorialspoint Selenium SQLServer Swift Solr SVN SQLite Socket Smarty Shell 教程

    它支持多种编程语言(如Java、Python、C#等),可以跨浏览器和平台进行测试。学习Selenium,你将了解如何编写测试脚本、执行自动化测试用例,以及如何利用其提供的各种API进行功能和回归测试。 2. **SQLServer**:...

Global site tag (gtag.js) - Google Analytics