ElasticSearch系列 - SpringBoot整合ES:指定搜索结果返回的字段_source

这篇具有很好参考价值的文章主要介绍了ElasticSearch系列 - SpringBoot整合ES:指定搜索结果返回的字段_source。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


Elasticsearch的搜索结果可以通过以下参数进行控制:

from:指定搜索结果的起始位置,默认为0。
size:指定返回的文档数量,默认为10。
sort:指定搜索结果的排序方式,可以按照字段升序或降序排列。
query:指定搜索的查询条件,可以使用各种查询语句进行搜索。
filter:指定搜索的过滤条件,可以使用各种过滤语句进行过滤。
highlight:指定搜索结果中需要高亮显示的字段。
aggregations:指定搜索结果的聚合方式,可以对搜索结果进行分组统计。
suggest:指定搜索建议,可以根据用户输入的关键词提供搜索建议。

1. 数据准备

PUT /my_index/_doc/1
{
  "title": "文雅酒店",
  "content": "青岛",
  "price": 556
}

PUT /my_index/_doc/2
{
  "title": "金都嘉怡假日酒店",
  "content": "北京",
  "price": 337
}

PUT /my_index/_doc/3
{
  "title": "金都欣欣酒店",
  "content": "天津",
  "price": 200
}

PUT /my_index/_doc/4
{
  "title": "金都酒店",
  "content": "北京",
  "price": 500
}

2. ElasticSearch 搜索结果返回指定的字段

在 ElasticSearch 中,可以使用 _source 字段来指定返回的字段。默认情况下,ElasticSearch 返回匹配文档的所有字段,但是可以通过 _source 字段来指定只返回需要的字段,这样可以减少网络传输和解析的开销,提高搜索性能。

以下是一个示例,假设我们有一个名为 my_index 的索引,其中包含 title 、content和price 这3个字段,我们只需要返回 title 字段:

GET /my_index/_search
{
  "_source": ["title"],
  "query": {
    "match": {
      "content": "北京"
    }
  }
}

在上面的示例中,我们使用 _source 字段来指定只返回 title 字段,同时使用 match 查询来搜索包含 北京 的文档。

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.3862944,
    "hits" : [
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.3862944,
        "_source" : {
          "title" : "金都嘉怡假日酒店"
        }
      },
      {
        "_index" : "my_index",
        "_type" : "_doc",
        "_id" : "4",
        "_score" : 1.3862944,
        "_source" : {
          "title" : "金都酒店"
        }
      }
    ]
  }
}

如果需要返回多个字段,可以将字段名添加到 _source 字段的数组中,如下所示:

GET /my_index/_search
{
  "_source": ["title", "content"],
  "query": {
    "match": {
      "content": "北京"
    }
  }
}

在上面的示例中,我们指定返回 title 和 content 两个字段。

需要注意的是,如果某个字段被存储在索引中,但是没有被指定在 _source 字段中,那么在搜索结果中将无法获取该字段的值。因此,在创建索引时,需要根据实际需求来决定哪些字段需要被存储在索引中。文章来源地址https://www.toymoban.com/news/detail-442676.html

3. SpringBoot整合ES 搜索结果返回指定的字段

@Slf4j
@Service
public class ElasticSearchImpl {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void searchUser() throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // query 参数
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("content","北京");
        searchSourceBuilder.query(matchQueryBuilder);

        // _source 参数
        searchSourceBuilder.fetchSource(new String[]{"title","content"},null);

        SearchRequest searchRequest = new SearchRequest(new String[]{"my_index"},searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 搜索结果
        SearchHits searchHits = searchResponse.getHits();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // hits.hits._source:匹配的文档的原始数据
            String sourceAsString = hit.getSourceAsString();
            System.out.println("sourceAsString = " + sourceAsString);
        }
        System.out.println(searchResponse);
    }
}
{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.3862944,
        "hits": [
            {
                "_index": "my_index",
                "_type": "_doc",
                "_id": "2",
                "_score": 1.3862944,
                "_source": {
                    "title": "金都嘉怡假日酒店",
                    "content": "北京"
                }
            },
            {
                "_index": "my_index",
                "_type": "_doc",
                "_id": "4",
                "_score": 1.3862944,
                "_source": {
                    "title": "金都酒店",
                    "content": "北京"
                }
            }
        ]
    }
}

4. 源码接口

public final class SearchSourceBuilder implements Writeable, ToXContentObject, Rewriteable<SearchSourceBuilder> {
    
    /**
     * Indicates whether the response should contain the stored _source for every hit
     */
    public SearchSourceBuilder fetchSource(boolean fetch) {
        FetchSourceContext fetchSourceContext = this.fetchSourceContext != null ? this.fetchSourceContext
            : FetchSourceContext.FETCH_SOURCE;
        this.fetchSourceContext = new FetchSourceContext(fetch, fetchSourceContext.includes(), fetchSourceContext.excludes());
        return this;
    }

    /**
     * Indicate that _source should be returned with every hit, with an
     * "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param include
     *            An optional include (optionally wildcarded) pattern to filter
     *            the returned _source
     * @param exclude
     *            An optional exclude (optionally wildcarded) pattern to filter
     *            the returned _source
     */
    public SearchSourceBuilder fetchSource(@Nullable String include, @Nullable String exclude) {
        return fetchSource(include == null ? Strings.EMPTY_ARRAY : new String[] { include }, exclude == null ? Strings.EMPTY_ARRAY
                           : new String[] { exclude });
    }

    /**
     * Indicate that _source should be returned with every hit, with an
     * "include" and/or "exclude" set which can include simple wildcard
     * elements.
     *
     * @param includes
     *            An optional list of include (optionally wildcarded) pattern to
     *            filter the returned _source
     * @param excludes
     *            An optional list of exclude (optionally wildcarded) pattern to
     *            filter the returned _source
     */
    public SearchSourceBuilder fetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
        FetchSourceContext fetchSourceContext = this.fetchSourceContext != null ? this.fetchSourceContext
            : FetchSourceContext.FETCH_SOURCE;
        this.fetchSourceContext = new FetchSourceContext(fetchSourceContext.fetchSource(), includes, excludes);
        return this;
    }

    /**
     * Indicate how the _source should be fetched.
     */
    public SearchSourceBuilder fetchSource(@Nullable FetchSourceContext fetchSourceContext) {
        this.fetchSourceContext = fetchSourceContext;
        return this;
    }
}

到了这里,关于ElasticSearch系列 - SpringBoot整合ES:指定搜索结果返回的字段_source的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Elasticsearch 核心技术(九):搜索结果处理(分页、排序、指定返回字段、去重、高亮显示)

    ❤️ 博客主页:水滴技术 🚀 支持水滴: 点赞 👍 + 收藏 ⭐ + 留言 💬 🌸 订阅专栏:大数据核心技术从入门到精通

    2023年04月13日
    浏览(69)
  • ElasticSearch序列 - SpringBoot整合ES:根据指定的 ids 查询

    1. ElasticSearch 根据 ids 查询文档 ① 索引文档,构造数据 ② 查询文档 id 为 1 或者 2 的文档: 我们索引文档时,文档的id为整型,为什么查询出来的文档 id为字符串类型呢?如果我们使用字符串类型的文档id查询呢? 可以看到仍然可以查询到匹配的文档。 在Elasticsearch中,文档

    2024年02月11日
    浏览(42)
  • 【Elasticsearch】SpringBoot整合ES实现搜索功能 | 高亮显示

    先看代码: controller: serviceImpl: 小结 : 1、添加ES场景启动器 2、yaml配置ES 3、准备需要用到的变量 注:还有一个注入的RestHighLevelClient 结构如下: 具体调用的方法以及设置页码等参看代码。 加断点查看对应searchResponse数据结构: HighlightFields的数据结构: 对照kinaba结果: 3、根

    2024年02月11日
    浏览(33)
  • ElasticSearch系列 - SpringBoot整合ES:ElasticSearch分析器

    1. ElasticSearch match 文本搜索的过程? Elasticsearch 的 match 查询是一种基于文本匹配的查询方式,它的搜索过程如下: ① 将查询字符串分词:Elasticsearch 会将查询字符串分成一个个词项(term),并去除停用词(如“的”、“是”等常用词汇)和标点符号等无意义的字符。 ② 构建

    2023年04月18日
    浏览(106)
  • 搜索引擎ElasticSearch分布式搜索和分析引擎学习,SpringBoot整合ES个人心得

    Elasticsearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。Elasticsearch用于云计算中,能够达到实时搜索,稳定,可靠,

    2024年02月04日
    浏览(53)
  • ElasticSearch系列 - SpringBoot整合ES:分析器

    1. ElasticSearch match 文本搜索的过程? Elasticsearch 的 match 查询是一种基于文本匹配的查询方式,它的搜索过程如下: ① 将查询字符串分词:Elasticsearch 会将查询字符串分成一个个词项(term),并去除停用词(如“的”、“是”等常用词汇)和标点符号等无意义的字符。 ② 构建

    2024年02月06日
    浏览(46)
  • ElasticSearch系列 - SpringBoot整合ES:多个精确值查询 terms

    ElasticSearch - SpringBoot整合ES:多个精确值查询 terms 01. ElasticSearch terms 查询支持的数据类型 在Elasticsearch中,terms查询支持多种数据类型,包括: 字符串类型:可以将多个字符串值作为数组传递给terms查询,以匹配包含任何一个指定字符串值的文档。 数值类型:可以将多个数值作

    2024年02月16日
    浏览(54)
  • ElasticSearch系列 - SpringBoot整合ES:组合多个查询条件 bool 查询

    01. ElasticSearch 布尔查询是什么? 在实际应用中,我们很有可能会查询多个值或字段。 一个 bool 查询由三部分组成: must:所有的语句都必须(must) 匹配,与 AND 等价。 must_not:所有的语句都不能(must not)匹配,与 NOT 等价。 should:至少有一个语句要匹配,与 OR 等价。 02.

    2023年04月08日
    浏览(50)
  • ElasticSearch系列 - SpringBoot整合ES:短语匹配查询 match_phrase

    1. ElasticSearch match_phrase查询是什么?它与match查询有什么区别? match_phrase查询是一种用于匹配短语的查询方式,可以用于精确匹配多个单词组成的短语。它会将查询字符串分解成单词,然后按照顺序匹配文档中的单词,只有当文档中的单词顺序与查询字符串中的单词顺序完全

    2024年02月12日
    浏览(36)
  • ElasticSearch系列 - SpringBoot整合ES:映射中定义字段的数据类型及属性

    ElasticSearch - SpringBoot整合ES:映射定义字段的数据类型及属性 01. ElasticSearch 搜索结果的准确性和召回率是什么? 在Elasticsearch中,搜索结果的准确性和召回率是非常重要的指标,它们反映了搜索引擎的性能和效果。以下是这两个指标的定义和解释: 准确性:搜索结果的准确性

    2024年02月08日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包