本文出自:http://blog.csdn.net/feelig/article/details/8499614

最大的特点: 
1. 数据库的 database, 就是  index 
2. 数据库的 table,  就是 tag 
3. 不要使用browser, 使用curl来进行客户端操作.  否则会出现 java heap ooxx...

curl:  -X 后面跟 RESTful :  GET, POST ... 
-d 后面跟数据。 (d = data to send)

1. create:

指定 ID 来建立新记录。 (貌似PUT, POST都可以) 
$ curl -XPOST localhost:9200/films/md/2 -d ' 
{ "name":"hei yi ren", "tag": "good"}'

使用自动生成的 ID 建立新纪录: 
$ curl -XPOST localhost:9200/films/md -d ' 
{ "name":"ma da jia si jia3", "tag": "good"}'

2. 查询: 
2.1 查询所有的 index, type: 
$ curl localhost:9200/_search?pretty=true

2.2 查询某个index下所有的type: 
$ curl localhost:9200/films/_search

2.3 查询某个index 下, 某个 type下所有的记录: 
$ curl localhost:9200/films/md/_search?pretty=true

2.4 带有参数的查询:  
$ curl localhost:9200/films/md/_search?q=tag:good 
{"took":7,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2,"max_score":1.0,"hits":[{"_index":"film","_type":"md","_id":"2","_score":1.0,

"_source" : 
{ "name":"hei yi ren", "tag": "good"}},{"_index":"film","_type":"md","_id":"1","_score":0.30685282, "_source" : 
{ "name":"ma da jia si jia", "tag": "good"}}]}}

2.5 使用JSON参数的查询: (注意 query 和 term 关键字) 
$ curl localhost:9200/film/_search -d ' 
{"query" : { "term": { "tag":"bad"}}}'

3. update  
$ curl -XPUT localhost:9200/films/md/1 -d { ...(data)... }

4. 删除。 删除所有的:

$ curl -XDELETE localhost:9200/films

角色关系对照

elasticsearch 跟 MySQL 中定义资料格式的角色关系对照表如下

MySQL             elasticsearch
database                 index
table                         type

table schema mapping
row                          document
field                         field

3.索引映射

#创建索引
$ curl -XPUT http://localhost:9200/test-index

#创建Mapping
$ curl -XPUT http://localhost:9200/test-index/test-type/_mapping -d '{
    "properties" : {
        "name" : { "type" : "string" }
    }
}'

@route('/indexsetting/')
def indexmapping():
    """索引映射"""
    conn = ES('127.0.0.1:9200')
    conn.debug_dump = True
    try:
        #删除索引
        conn.delete_index("test-index")
    except:
        pass
    #创建索引
    conn.create_index("test-index")
    mapping = {
           u'id': {'store': 'yes',
                    'type': u'integer'},
           u'author': {'boost': 1.0,
                       'index': 'not_analyzed',
                       'store': 'yes',
                       'type': u'string'},
           u'published': {'boost': 1.0,
                          'index': 'not_analyzed',
                          'store': 'yes',
                          'type': u'datetime'},
           u'url': {'store': 'yes',
                    'type': u'string'},
           u'title': {'boost': 1.0,
                       'index': 'analyzed',
                       'store': 'yes',
                       'type': u'string'},
           u'content': {'boost': 1.0,
                       'index': 'analyzed',
                       'store': 'yes',
                       'type': u'string',
                       "term_vector" : "with_positions_offsets"}
           }
    #索引映射
    conn.put_mapping("test-type", {'properties':mapping}, ["test-index"])
    return "索引映射"

4.索引

#索引
$ curl -XPUT http://localhost:9200/test-index/test-type/1 -d '{
    "user": "kimchy",
    "post_date": "2009-11-15T13:12:00",
    "message": "Trying out elasticsearch, so far so good?"
}'

#获取
$ curl -XGET http://localhost:9200/test-index/test-type/1

#删除
$ curl -XDELETE 'http://localhost:9200/test-index/test-type/1'

@route('/indextest/')
def indexTest():
    """索引测试"""
    conn = ES('127.0.0.1:9200')
    for item in Data().getData():
        #添加索引
        conn.index(item,"test-index", "test-type",item['id'])

#索引优化
    conn.optimize(["test-index"])
    #删除索引内容
    conn.delete("test-index", "test-type", 2668090)
    #更新索引内容
    model = conn.get("test-index", "test-type", 2667371)
    model["title"]="标题修改测试"
    conn.update(model,"test-index", "test-type",2667371)

#刷新索引
    conn.refresh(["test-index"])

q = MatchAllQuery()
    results = conn.search(query = q,indices="test-index",doc_types="test-type")
#    for r in results:
#        print r
    return template('default.tpl', list=results,count=len(results))

5.搜索

#lucene语法方式的查询
$ curl -XGET http://localhost:9200/test-index/test-type/_search?q=user:kimchy

#query DSL方式查询
$ curl -XGET http://localhost:9200/test-index/test-type/_search -d '{
    "query" : {
        "term" : { "user": "kimchy" }
    }
}'

#query DSL方式查询
$ curl -XGET http://localhost:9200/test-index/_search?pretty=true -d '{
    "query" : {
        "range" : {
            "post_date" : {
                "from" : "2009-11-15T13:00:00",
                "to" : "2009-11-15T14:30:00"
            }
        }
    }
}'

#查找全部索引内容
$ curl -XGET http://localhost:9200/test-index/test-type/_search?pretty=true

@route('/search/')
@route('/search/<searchkey>')
def search(searchkey=u"关键算法"):
    """索引搜索"""
    conn = ES('127.0.0.1:9200')

#TextQuery会对searchkey进行分词
    qtitle = TextQuery("title", searchkey)
    qcontent = TextQuery("content", searchkey)
    #发布时间大于"2012-9-2 22:00:00"
    qpublished=RangeQuery(ESRangeOp("published", "gt", datetime(2012, 9,2, 22, 0, 0)))

h = HighLighter(['<b>'], ['</b>'], fragment_size=500)
    #多字段搜索(must=>and,should=>or),高亮,结果截取(分页),排序
    q = Search(BoolQuery(must=[qpublished],should=[qtitle,qcontent]),highlight=h, start=0, size=3, sort={'id': {'order': 'asc'}})
    q.add_highlight("title")
    q.add_highlight("content")
    results = conn.search(query = q,indices="test-index",doc_types="test-type")

list=[]
    for r in results:
        if(r._meta.highlight.has_key("title")):
            r['title']=r._meta.highlight[u"title"][0]
        if(r._meta.highlight.has_key("content")):
            r['content']=r._meta.highlight[u"content"][0]
        list.append(r)
    return template('search.tpl', list=list,count=results.total)

6.设置

#创建索引,并设置分片和副本参数
$ curl -XPUT http://localhost:9200/elasticsearch/ -d '{
    "settings" : {
        "number_of_shards" : 2,
        "number_of_replicas" : 3
    }
}'

7.其他

#分词
curl -XGET 'http://localhost:9200/test-index/_analyze?text=中华人民共和国'

elasticsearch的基本用法(转载)的更多相关文章

  1. C# DataSet与DataTable的区别和用法 ---转载

    C# DataSet与DataTable的区别和用法 转载:https://www.cnblogs.com/liuyi-li/p/6340411.html DataSet是数据集,DataTable是 ...

  2. ElasticSearch的基本用法与集群搭建

    一.简介 ElasticSearch和Solr都是基于Lucene的搜索引擎,不过ElasticSearch天生支持分布式,而Solr是4.0版本后的SolrCloud才是分布式版本,Solr的分布式 ...

  3. 移动端下拉刷新,iScroll.js用法(转载)

    本文转载自: iScroll.js 用法参考 (share)

  4. ES6 Promise 用法转载

    Promise是一个构造函数,自己身上有all.reject.resolve这几个眼熟的方法,原型上有then.catch等同样很眼熟的方法. 那就new一个 var p = new Promise( ...

  5. python---map 用法 [转载]

    map()函数 map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 1.当seq只 ...

  6. Elasticsearch批量操作API用法介绍

    Elasticsearch的Bulk API允许批量提交index和delete请求,有如下两种用法: 用法1 BulkRequestBuilder requestBuilder = client.p ...

  7. SQL中CASE 的用法 转载

    sql语言中有没有类似C语言中的switch case的语句?? 没有,用case   when   来代替就行了.              例如,下面的语句显示中文年月 select getdat ...

  8. ElasticSearch的基本用法与集群搭建 good

    一.简介 ElasticSearch和Solr都是基于Lucene的搜索引擎,不过ElasticSearch天生支持分布式,而Solr是4.0版本后的SolrCloud才是分布式版本,Solr的分布式 ...

  9. AutoMapper用法 转载https://www.cnblogs.com/youring2/p/automapper.html

    AutoMapper是对象到对象的映射工具.在完成映射规则之后,AutoMapper可以将源对象转换为目标对象. 配置AutoMapper映射规则 AutoMapper是基于约定的,因此在实用映射之前 ...

随机推荐

  1. NX二次开发-基于MFC界面对话框与NX交互的开发

    打开VS2013 点击新建,选择MFC DLL 点击确定 点下一步 什么都不改,直接点完成 进来之后先编译一下,看是否编译成功 打开项目属性,更改这几处 $(UGII_BASE_DIR)\ugopen ...

  2. word文档操作

    1.如何把word文档修改的地方标记出来   :  https://zhidao.baidu.com/question/73648149.html 2.word 的几种 视图:https://zhid ...

  3. error LNK2019: 无法解析的外部符号 __imp__GetStockObject@4该符号在函数_WinMain@16 中被引用

    编译链接报错 error LNK2019: 无法解析的外部符号 __imp__GetStockObject@4该符号在函数_WinMain@16 中被引用 解决方案: 在代码中添加链接库gdi32.l ...

  4. 22. Jmeter NON GUI模式

    一般情况下我们都是在NonGUI模式下运行jmeter.这样做有两个好处 节省系统资源,能够产生更大的负载 可以通过命令行参数对测试场景进行更精细的配置 需求:模拟5个用户同时访问百度首页的情况 步骤 ...

  5. 18、Page Object 设计模式

    Page Object 设计模式的优点如下: 减少代码的重复. 提高测试用例的可读性. 提高测试用例的可维护性, 特别是针对 UI 频繁变化的项目. 当你针对网页编写测试时,你需要引用该网页中的元素, ...

  6. shell 检查文件夹是否包含文件,或者只是空文件

    empty_dir_check(){ check_dir=$ if [ -d $check_dir ];then file_list=` -maxdepth -type f` if [ $file_l ...

  7. 【Java多线程系列五】列表类

    一些列表类及其特性  类 线程安全 Iterator 特性 说明 Vector 是 fail-fast 内部方法用synchronized修饰,因此执行效率较低 1. 线程安全的列表类并不意味着调用它 ...

  8. 常用命令--sed

    sed -n '/2019-07-24/,/2019-07-25/p' my.log sed -n '/2019-07-25 16:51:23,699/,/2019-07-25 16:51:38,79 ...

  9. [Code+#3]博弈论与概率统计

    题目 记得曾经和稳稳比谁后抄这个题的题解,看来是我输了 不难发现\(p\)是给着玩的,只需要求一个总情况数除以\(\binom{n+m}{n}\)就好了 记\(i\)为无效的失败次数,即\(\rm A ...

  10. IDEA 创建Spring cloud Eureka 注册中心

    IDEA 创建Spring cloud Eureka 注册中心 一. 首先创建一个maven project Next之后填好groupId与artifactId,Next之后填好项目名与路径,点击F ...