ElasticSearch:仅索引映射中指定的字段

6 投票
1 回答
3086 浏览
提问于 2025-04-17 11:11

我有一个ElasticSearch的设置,它通过CouchDB river接收数据进行索引。我的问题是,CouchDB文档中的大多数字段其实和搜索没什么关系:它们是应用程序内部使用的字段(比如ID等等),我不想因为这些字段而得到错误的搜索结果。此外,索引那些不需要的数据对我来说也是一种资源浪费。

为了解决这个问题,我定义了一个映射,指定我想要被索引的字段。我使用pyes来访问ElasticSearch。我遵循的步骤是:

  1. 创建CouchDB river,并将其关联到一个索引。这似乎也会创建索引,并在该索引中创建一个“couchdb”映射,按照我所看到的,它包含了所有字段,并且类型是动态分配的。
  2. 设置一个映射,限制到我真正想要索引的字段。

这是我获得的索引定义:

curl -XGET http://localhost:9200/notes_index/_mapping?pretty=true

{
  "notes_index" : {
    "default_mapping" : {
      "properties" : {
        "note_text" : {
          "type" : "string"
        }
      }
    },
    "couchdb" : {
      "properties" : {
        "_rev" : {
          "type" : "string"
        },
        "created_at_date" : {
          "format" : "dateOptionalTime",
          "type" : "date"
        },
        "note_text" : {
          "type" : "string"
        },
        "organization_id" : {
          "type" : "long"
        },
        "user_id" : {
          "type" : "long"
        },
        "created_at_time" : {
          "type" : "long"
        }
      }
    }
  }
}

我面临的问题有很多:

  • 默认的“couchdb”映射正在索引所有字段。我不想这样。有没有办法避免创建这个映射?我感到困惑,因为这个映射似乎是某种程度上“连接”到CouchDB river的。
  • 我创建的映射似乎没有任何效果:没有文档被这个映射索引。

你有什么建议吗?

编辑

这是我实际在做的,完全按照我输入的内容:

server="localhost"

# Create the index
curl -XPUT    "$server:9200/index1"

# Create the mapping
curl -XPUT    "$server:9200/index1/mapping1/_mapping" -d '
{
    "type1" : {
        "properties" : {
            "note_text" : {"type" : "string", "store" : "no"}
        }
    }
}
'

# Configure the river
curl -XPUT "$server:9200/_river/river1/_meta" -d '{
    "type" : "couchdb",
    "couchdb" : {
        "host" : "localhost",
        "port" : 5984,
        "user" : "admin",
        "password" : "admin",
        "db" : "notes"
    },
    "index" : {
        "index" : "index1",
        "type" : "type1"
    }
}'

在index1中的文档仍然包含“note_text”以外的字段,而“note_text”是我在映射定义中明确提到的唯一字段。为什么会这样呢?

1 个回答

0

CouchDB river的默认行为是使用“动态”映射,也就是说,它会把所有在CouchDB文档中找到的字段都索引起来。你说得对,这样可能会不必要地增加索引的大小(你在搜索时遇到的问题可以通过在查询中排除一些字段来解决)。

如果你想使用自己定义的映射,而不是“动态”的那种,你需要配置River插件,让它使用你创建的映射(可以参考这篇文章):

curl -XPUT 'elasticsearch-host:9200/_river/notes_index/_meta' -d '{
    "type" : "couchdb",

    ... your CouchDB connection configuration ...

    "index" : {
        "index" : "notes_index",
        "type" : "mapping1"
    }
}'

在做映射时,你在URL中指定的类型名称PUT会覆盖你在定义中包含的类型,所以你创建的类型实际上是mapping1。试着执行这个命令,看看结果如何:

> curl 'localhost:9200/index1/_mapping?pretty=true'

{
  "index1" : {
    "mapping1" : {
      "properties" : {
        "note_text" : {
          "type" : "string"
        }
      }
    }
  }
}

我认为如果你把类型名称弄对了,它就会正常工作。

撰写回答