随笔 - 15  文章 - 0  评论 - 0  阅读 - 28万

elasticsearch中的mapping映射配置与查询典型案例

elasticsearch中的mapping映射配置示例
比如要搭建个中文新闻信息的搜索引擎,新闻有"标题"、"内容"、"作者"、"类型"、"发布时间"这五个字段;
我们要提供"标题和内容的检索"、"排序"、"高亮"、"统计"、"过滤"等一些基本功能。
ES提供了smartcn的中文分词插件,测试的话建议使用IK分词插件。
内容中properties对应mapping里的内容,里面5个字段。
type指出字段类型、内容、标题字段要进行分词和高亮因此要设置分词器和开启term_vector。
{
  "news": {
    "properties": {
      "content": {#内容
        "type": "string",  #字段类型
        "store": "no", #是否存储
        "term_vector": "with_positions_offsets",#开启向量,用于高亮
        "index_analyzer": "ik",#索引时分词器
        "search_analyzer": "ik"#搜索时分词器
      },
      "title": {
        "type": "string",
        "store": "no",
        "term_vector": "with_positions_offsets",
        "index_analyzer": "ik",
        "search_analyzer": "ik",
        "boost": 5
      },
      "author": {
        "type": "string",
        "index": "not_analyzed"#该字段不分词
      },
      "publish_date": {
        "type": "date",
        "format": "yyyy/MM/dd",
        "index": "not_analyzed"#该字段不分词
      },
      "category": {
        "type": "string",
        "index": "not_analyzed"#该字段不分词
      }
    }
  }
}

查询示例:内容包括几个部分:

分页:from/size、字段:fields、排序sort、查询:query、过滤:filter、高亮:highlight、统计:facet
{
  "from": 0,
  "size": 10,
  "fields": [
    "title",
    "content",
    "publish_date",
    "category",
    "author"
  ],
  "sort": [
    {
      "publish_date": {
        "order": "asc"
      }
    },
    "_score"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "title": "中国"
          }
        },
        {
          "term": {
            "content": "中国"
          }
        }
      ]
    }
  },
  "filter": {
    "range": {
      "publish_date": {
        "from": "2010/07/01",
        "to": "2010/07/21",
        "include_lower": true,
        "include_upper": false
      }
    }
  },
  "highlight": {
    "pre_tags": [
      "<tag1>",
      "<tag2>"
    ],
    "post_tags": [
      "</tag1>",
      "</tag2>"
    ],
    "fields": {
      "title": {},
      "content": {}
    }
  },
  "facets": {
    "cate": {
      "terms": {
        "field": "category"
      }
    }
  }
}
结果包含需要的几个部分。
值得注意的是,facet的统计是命中的结果进行统计,filter是对结果进行过滤,filter不会影响facet,如果要统计filter掉的的就要使用filter facet。

posted on   天际霄鹰  阅读(10978)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示