Как определить текстовые индексы mongodb в mgo с весами

Я пытаюсь создать текстовые индексы с весами, но я не мог понять, как это сделать, читая документы API.

Как я могу построить индексы, как показано ниже, в mgo.

db.products.createIndex({
  "primaryCategoryIndexes": "text",
  "secondaryCategoryIndexes": "text",
  "brandIndex": "text",
  "primaryTitleIndexes": "text",
  "secondaryTitleIndexes": "text",
  "indexCycleId": "text"
  }, {
    "weights": {
      "primaryCategoryIndexes":10,
      "secondaryCategoryIndexes": 5,
      "brandIndex": 5,
      "primaryTitleIndexes": 5,
      "secondaryTitleIndexes": 5, 
      "indexCycleId": 5
  })

person Lupus    schedule 04.01.2018    source источник
comment
Возможный дубликат Как создать текстовый индекс в mongodb с помощью golang и библиотеки mgo?   -  person Marc    schedule 04.01.2018
comment
@Марк, спасибо за указание, но этот ответ не включает веса.   -  person Lupus    schedule 04.01.2018


Ответы (1)


По какой-то странной причине прямой ответ на этот вопрос в комментарии удален. Я стараюсь не вдаваться в это, но я думаю, что лучше всего опубликовать ответ.

Можно использовать поле в mgo.Index для выполнения работы. Однако некоторая версия моего не поддерживает это.

Прочтите руководство: https://godoc.org/gopkg.in/mgo.v2#Index

type Index struct {
    Key        []string // Index key fields; prefix name with dash (-) for descending order
    Unique     bool     // Prevent two documents from having the same index key
    DropDups   bool     // Drop documents with the same index key as a previously indexed one
    Background bool     // Build index in background and return immediately
    Sparse     bool     // Only index documents containing the Key fields

    // If ExpireAfter is defined the server will periodically delete
    // documents with indexed time.Time older than the provided delta.
    ExpireAfter time.Duration

    // Name holds the stored index name. On creation if this field is unset it is
    // computed by EnsureIndex based on the index key.
    Name string

    // Properties for spatial indexes.
    //
    // Min and Max were improperly typed as int when they should have been
    // floats.  To preserve backwards compatibility they are still typed as
    // int and the following two fields enable reading and writing the same
    // fields as float numbers. In mgo.v3, these fields will be dropped and
    // Min/Max will become floats.
    Min, Max   int
    Minf, Maxf float64
    BucketSize float64
    Bits       int

    // Properties for text indexes.
    DefaultLanguage  string
    LanguageOverride string

    // Weights defines the significance of provided fields relative to other
    // fields in a text index. The score for a given word in a document is derived
    // from the weighted sum of the frequency for each of the indexed fields in
    // that document. The default field weight is 1.
    Weights map[string]int

    // Collation defines the collation to use for the index.
    Collation *Collation
}

Кстати, что касается golang, то есть godoc.org и go-serach.org для поиска go libs, и они в целом превосходят Google.

person leaf bebop    schedule 04.01.2018
comment
godoc.org/labix.org/v2/mgo#Index Выполнить Ctrl+ F и вставьте Weights, пожалуйста, продолжайте... - person Lupus; 05.01.2018
comment
Теперь я знаю, почему раньше не видел поле Weights. Потому что его даже нет изначально. Потому что, когда вы вводите mgo Index в Google, вы получаете эту документацию. До сих пор я думал, что пропустил это. О чувак! Это так меня облегчило. Я должен поблагодарить вашу одержимость. Если бы вы не были так одержимы, я бы не понял этого факта и подумал, что вы, вероятно, правы. Вы можете себе это представить. - person Lupus; 05.01.2018
comment
Я не ожидал этого. Прошу прощения за то, что был слишком резок с вами. Тем не менее, я предлагаю в следующий раз, чтобы избежать таких ситуаций, пожалуйста, прикрепите то, что вы пробовали, в вопросах, как предлагают рекомендации по переполнению стека. - person leaf bebop; 05.01.2018
comment
Ссылка на годок. - person Lupus; 05.01.2018
comment
Я имею в виду, что у godoc есть поисковая система, и вы можете искать прямо из нее. - person leaf bebop; 05.01.2018