python3从ES中以分词方式查询数据并实现分页的demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32502511/article/details/86505225

实现效果:前提是已经配置好了ES IK分词扩展的和创建好了索引并导入了数据的情况下,实现分页查询。demo代码如下:

from elasticsearch import Elasticsearch
'''
@:param page_szie:每页显示条数
@:param page_index:当前第几页
@:param where_list:查询条件,格式如:[{"article_content":"成都"},{"article_title":"北京"}]
'''
def get_data(page_szie,page_index,where_list):
    result = {}
    try:
        #连接Elasticsearch
        es = Elasticsearch([{'host':'192.168.16.11','port':9200}])
        from_index=page_szie*(page_index-1)
        #条件拼接
        should = []
        for x in where_list:
            item = {"match": {
                list(x.keys())[0]: {
                    "query": list(x.values())[0],
                    "analyzer": "ik_smart"
                }}}
            should.append(item)
        body={
            "query":{
                "bool":{
                        "must":[
                            {
                               "bool":{
                                   "should":should
                               }

                            },
                        ],
                    }
                },
                "from":from_index,   #起始位置
                "size": page_szie,  #每页条数
                "sort":{"article_time":"desc"} #排序字段和排序方式
        }
        res=es.search(index="article_all_new",body=body,doc_type="doc")
        count=res["hits"]["total"]
        result["page_szie"]=page_szie
        result["page_index"]=page_index
        result["total"]=count
        result["total_page"]=int(count/page_szie) if count%page_szie==0 else int(int(count/page_szie)+1)
        result["code"]=0
        result["list"]=res["hits"]["hits"]
        return result
    except Exception as ex:
        result["code"] = -1
        return result


lis=[{"article_content":"成都双流"},{"article_title":"北京"}]
data=get_data(5,2,lis)
print(data)

运行返回结果如图:

猜你喜欢

转载自blog.csdn.net/qq_32502511/article/details/86505225