elasticsearch返回指定字段

ε祈祈猫儿з 提交于 2020-08-05 06:18:29

1. postman 请求elasticsearch 返回指定字段

  1.直接在请求体当中,json 数据,对应的是一个列表

复制代码
{

  "_source":['title','id','desc'],
  "from":10,
  "size":100,

}
复制代码

   至于from和size是浅分页

    2. 或者这样

复制代码
{
    "_source":{
        "includes":["title","url","id"],
        "excludes":["desc"]
    }
}
复制代码

  其中includes代表需要返回的字段,excludes代表不要返回的字段

  3.直接在请求url带上需要查询参数

curl -XGET 'localhost:9200/_search?pretty&filter_path=took,hits.hits._id,hits.hits._score'
复制代码
{
  "took" : 3,
  "hits" : {
    "hits" : [
      {
        "_id" : "3640",
        "_score" : 1.0
      },
      {
        "_id" : "3642",
        "_score" : 1.0
      }
    ]
  }
}
复制代码

  对_source的字段进行过滤

curl -XGET 'localhost:9200/_search?pretty&filter_path=hits.hits._source&_source=title'
复制代码
{
  "hits" : {
    "hits" : [ {
      "_source":{"title":"Book #2"}
    }, {
      "_source":{"title":"Book #1"}
    }, {
      "_source":{"title":"Book #3"}
    } ]
  }
}
复制代码

   这样也可以

_search?_source=goodsId,uri

_search?fields=goodsId,uri

 

2.python 对接elassearch ,指定返回字段

  1.实例化的es客户端,然后调用search方法,传入参数,params


 
from elasticsearch import Elasticsearch
es=Elasticseach(xxxx) es.search(params={"_source":"title,id,desc,url"})

   注:这边调用的是包中的search方法,和postman不一样的是,_source的值是一个z字符串,不同字段用逗号隔开,而post满是一个列表

   2.也是调用Elasticsearch的search方法,传入参数不是param,而直接是_source字段

pprint(es.search(index='person', body={"query": {"match": {"age": "19"}}}, _source=['name']))

  结果:

复制代码
{'_shards': {'failed': 0, 'skipped': 0, 'successful': 1, 'total': 1},
 'hits': {'hits': [{'_id': 'xFznIXIBMTX0DMkCyicV',
                    '_index': 'person',
                    '_score': 1.0,
                    '_source': {'name': 'lisi'},
                    '_type': 'male'}],
          'max_score': 1.0,
          'total': {'relation': 'eq', 'value': 1}},
 'timed_out': False,
 'took': 1}
复制代码

 

 

3.不懂直接查询api接口

  https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html

 

4.返回文档版本字段

复制代码
GET /_search
{
    "version": true,
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}
复制代码

 

5.Script Field 用脚本来对命中的每个文档的字段进行运算后返回

复制代码
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "test1": {
      "script": {
        "lang": "painless",
        "source": "doc['balance'].value * 2"
      }
    },
    "test2": {
      "script": {
        "lang": "painless",
        <!--  doc指文档-->
        "source": "doc['age'].value * params.factor",
        "params": {
          "factor": 2
        }
      }
    } }}
复制代码

  搜索结果:

复制代码
{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1000,
    "max_score": 1,
    "hits": [
      {
        "_index": "bank",
        "_type": "_doc",
        "_id": "25",
        "_score": 1,
        "fields": {
          "test1": [
          ],
          "test2": [
          ]
        }
      },
      {
        "_index": "bank",
        "_type": "_doc",
        "_id": "44",
        "_score": 1,
        "fields": {
          "test1": [
          ],
          "test2": [
          ]
        }
      }
      }
    ]
  }
}
复制代码

  示例2

复制代码
 
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "ffx": {
      "script": {
        "lang": "painless",
        "source": "doc['age'].value * doc['balance'].value"
      }
    },
    "balance*2": {
      "script": {
        "lang": "painless",
        "source": "params['_source'].balance*2"
      }
    }
  }
}
复制代码

  搜索结果:

复制代码
{
  "took": 26,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1000,
    "max_score": 1,
    "hits": [
      {
        "_index": "bank",
        "_type": "_doc",
        "_id": "25",
        "_score": 1,
        "fields": {
          "balance*2": [
          ],
          "ffx": [
          ]
        }
      },
      {
        "_index": "bank",
        "_type": "_doc",
        "_id": "44",
        "_score": 1,
        "fields": {
          "balance*2": [
          ],
          "ffx": [
          ]
        }
      },

      }
    ]
  }
}
 

  

  说明: params  _source 取 _source字段值

  官方推荐使用doc,理由是用doc效率比取_source 高

 

package com.query.test;

import java.net.InetAddress;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import com.es.allpeizhi.EsAll;

/**
 * 文件名 : ElasticSearchBulkIn.java
 * 包 名 :
 * 描 述 : 过滤字段查询,指定返回字段数据
 * 机能名称:
 * 技能ID :
 * 作 者 : smkj
 * 版 本 : V1.0
 */
public class searchGuolv {
    @Test
    public static void main(String[] args) throws Exception {
        EsAll esall = new EsAll();
        // 查询关键字
        String searchName = "重庆市政府采购网";
        Long nowTime = System.currentTimeMillis();
        
        InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName(esall.host), esall.prot);
        // 配置settiong
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();
        
        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(node);
        System.out.println("ES--ip地址:" + node.getAddress());
        
        String index = esall.IndexName;
        String type = esall.TypeName;
        // 指定要返回的字段
        String[] fields = new String[1];
        fields[0] = "TITLE"; // 字段1名称
        // 构造query
        SearchRequestBuilder requestBuilder = client.prepareSearch(index);
        // setFields 2.x版本
        requestBuilder.setFrom(0).setSize(10).setTimeout(TimeValue.timeValueMillis(10)).setTypes(type).setFetchSource(fields, null);// 排除字段null
        ;
        // bool 条件
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        MatchPhraseQueryBuilder tqb = QueryBuilders.matchPhraseQuery("DISPLAY_CONTENT", keword);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        MatchPhraseQueryBuilder tqb = QueryBuilders.matchPhraseQuery("DISPLAY_CONTENT", searchName);
        
        boolQueryBuilder.must(tqb);
        // set query
        requestBuilder.setQuery(boolQueryBuilder);
        // get response
        SearchResponse response = requestBuilder.execute().actionGet();
        // 遍历返回的字段
        SearchHits searchHits = response.getHits();
//        List<String> id = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            System.out.println(hit.getSource().get("TITLE"));
//            System.out.println(hit.getFields().get("TITLE").getValue().toString());//2.x版本
        }
        client.close();
        System.out.println("命中总数量:" + response.getHits().getTotalHits());
        
//        System.out.println(id.size());
        System.out.println("耗时:" + (System.currentTimeMillis() - nowTime) / 1000 + "秒");
    }
    
}
————————————————

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!