zoukankan      html  css  js  c++  java
  • python使用es的例子(记录下)

    from elasticsearch import Elasticsearch
    
    esUrl = 'http://localhost:9200'
    
    es = Elasticsearch(esUrl)
    
    index = 'users'
    
    # 创建索引
    
    if (es.indices.exists(index) == False):
        mapping = {
            'dynamic':'',#自动创建索引
            'properties': {
                'title': {
                    'type': 'text',
                    'analyzer': 'ik_max_word',
                    'search_analyzer': 'ik_max_word'
                },
                'url': {
                    'type': 'string'
                },
                'date': {
                    'type': 'date'
                }
            }
        }
        result = es.indices.create(index)
        es.indices.analyze(index, body=mapping)
    
    datas = [
        {
            'title': '美国留给伊拉克的是个烂摊子吗',
            'url': 'http://view.news.qq.com/zt2011/usa_iraq/index.htm',
            'date': '2011-12-16',
        }, {
            'title': '公安部:各地校车将享最高路权',
            'url': 'http://www.chinanews.com/gn/2011/12-16/3536077.shtml',
            'date': '2011-12-16',
        }, {
            'title': '中韩渔警冲突调查:韩警平均每天扣1艘中国渔船',
            'url': 'https://news.qq.com/a/20111216/001044.htm',
            'date': '2011-12-17',
        }, {
            'title': '中国驻洛杉矶领事馆遭亚裔男子枪击嫌犯已自首',
            'url': 'http://news.ifeng.com/world/detail_2011_12/16/11372558_0.shtml',
            'date': '2011-12-18',
        }
    ]
    
    for k, row in enumerate(datas):
        es.index(index, body=row, doc_type='user', id=(k + 1))
    
    search = {
        'query': {
            'match': {
                'title': '各地校车 将享'
            }
        },
        'highlight': {
            'fields': {
                'title': {}
            }
        }
    }
    
    '''定制 highlight
    
    下面的参数可以改变返回的结果。即可以为单独的字段设置不同的参数,也可以作为 highlight 的属性统一定义。
    
    number_of_fragments
            fragment 是指一段连续的文字。返回结果最多可以包含几段不连续的文字。默认是5。
    
    fragment_size
           一段 fragment 包含多少个字符。默认100。
    
    pre_tags
           标记 highlight 的开始标签。例如上面的<em>。
    
    post_tags
           标记 highlight 的结束标签。例如上面的</em>。
    
    encoder
           说明字段是否为 html 格式,default:不是,html: 是。
    
    no_match_size
           即使字段中没有关键字命中,也可以返回一段文字,该参数表示从开始多少个字符被返回。'''
    
    result = es.search(index, search)
    print(result)
  • 相关阅读:
    关于C#的委托与事件的重新认识
    linux 下添加,修改,删除路由
    反射获取程序集的信息
    原创:2016.4.252016.5.1 C# informal essay and tittle_tattle
    原创:C sharp 中 Enum的几点小 Tips
    转:Dictionary<int,string>怎么获取它的值的集合?急!急!急!
    转:C#整数三种强制类型转换int、Convert.ToInt32()、int.Parse()的区别
    转:C#: static关键字的作用
    新博客 Fighting
    Win10系统下在国内访问Tensorflow官网
  • 原文地址:https://www.cnblogs.com/tudou1223/p/11504663.html
Copyright © 2011-2022 走看看