Непоследовательное поведение Elasticsearch с несколькими условиями must_not - PullRequest
0 голосов
/ 29 ноября 2018

Я работаю над API на основе NodeJ, и он построен с использованием Elasticsearch и NodeJ.Я должен предоставить функциональность, позволяющую пользователям API исключать некоторый контент на основе условий таксономии.

произвольная форма: Поле с несколькими значениями - тип: строка

игры: поле с несколькими значениями - тип: строка

игроки: поле с несколькими значениями - тип: строка

команды: мультиполе значения - тип: строка

записывающее устройство: поле с несколькими значениями - тип: строка

каналы: поле с несколькими значениями - тип:строка

Формат URL API будет примерно таким, как показано ниже.https://api.test.net/2/xxxxx/article/?exclude=term1+term2

Выше должно возвращать содержимое, которое не помечено для term1 и term2.

Предположим, у нас есть 3 статьи, первая статья помечена как term1, вторая статья помечена как term2 и третьястатья помечена для term1 и term2.

Ожидаемый результат: https://api.test.net/2/xxxxx/article/?exclude=term1+term2 должен возвращать статью первой (помеченную в term1), вторую статью (помеченную в term2), а не третью(Помечено на term1 и term2)

Фактический результат: Иногда https://api.test.net/2/xxxxx/article/?exclude=term1+term2 возвращает все три статьи, а иногда и первую (с тегом term1) и вторую статью (с тегом term2).

Обновление: Ниже приведен правильный документ, и я также добавил запрос, но все еще наблюдаю несоответствие.

Документ:

{
   "team":{
      "mappings":{
         "article":{
            "properties":{
               "body":{
                  "properties":{
                     "content":{
                        "type":"string"
                     },
                     "html":{
                        "type":"string"
                     },
                     "type":{
                        "type":"string"
                     }
                  }
               },
               "brand":{
                  "type":"string"
               },
               "changed":{
                  "type":"date",
                  "format":"dateOptionalTime"
               },
               "changedUtc":{
                  "type":"long"
               },
               "content":{
                  "type":"string"
               },
               "created":{
                  "type":"date",
                  "format":"dateOptionalTime"
               },
               "createdUtc":{
                  "type":"long"
               },
               "domain":{
                  "type":"string"
               },
               "headline":{
                  "type":"string"
               },
               "langcode":{
                  "type":"string",
                  "index":"not_analyzed"
               },
               "nid":{
                  "type":"string"
               },
               "published":{
                  "type":"date",
                  "format":"dateOptionalTime"
               },
               "publishedUtc":{
                  "type":"long"
               },
               "raw":{
                  "type":"string",
                  "index":"no"
               },
               "revisionTimestamp":{
                  "type":"date",
                  "format":"dateOptionalTime"
               },
               "revisionTimestampUtc":{
                  "type":"long"
               },
               "status":{
                  "type":"string"
               },
               "subheadline":{
                  "type":"string"
               },
               "syndication":{
                  "properties":{
                     "brand":{
                        "type":"string"
                     },
                     "options":{
                        "properties":{
                           "actionFrom":{
                              "type":"string"
                           },
                           "publish":{
                              "type":"string"
                           },
                           "status":{
                              "type":"string"
                           }
                        }
                     },
                     "type":{
                        "type":"string"
                     }
                  }
               },
               "taxonomy":{
                  "properties":{
                     "coaches":{
                        "properties":{
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "freeform":{
                        "properties":{
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "games":{
                        "properties":{
                           "id":{
                              "type":"string"
                           },
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "players":{
                        "properties":{
                           "id":{
                              "type":"string"
                           },
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "section":{
                        "properties":{
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "teams":{
                        "properties":{
                           "city":{
                              "type":"string"
                           },
                           "id":{
                              "type":"string"
                           },
                           "nickname":{
                              "type":"string"
                           },
                           "tricode":{
                              "type":"string"
                           },
                           "urlName":{
                              "type":"string"
                           },
                           "value":{
                              "type":"string"
                           }
                        }
                     },
                     "writer":{
                        "properties":{
                           "emailAddress":{
                              "type":"string"
                           },
                           "id":{
                              "type":"string"
                           },
                           "responsive_web":{
                              "type":"string"
                           },
                           "title":{
                              "type":"string"
                           },
                           "value":{
                              "type":"string"
                           }
                        }
                     }
                  }
               },
               "teaser":{
                  "type":"string"
               },
               "title":{
                  "type":"string"
               },
               "type":{
                  "type":"string"
               },
               "url":{
                  "type":"string",
                  "index":"not_analyzed"
               },
               "uuid":{
                  "type":"string",
                  "index":"not_analyzed"
               },
               "vid":{
                  "type":"string"
               }
            }
         }
      }
   }
}

Запрос:

{
   "filter":{
      "bool":{
         "should":[
            [
               {
                  "term":{
                     "status":1
                  }
               }
            ]
         ],
         "must":[

         ]
      }
   },
   "from":0,
   "size":10,
   "_source":{
      "include":[
         "uuid",
         "nid",
         "type",
         "title",
         "headline",
         "shortHeadline",
         "teaser",
         "url",
         "published",
         "changed",
         "subheadline",
         "listImage",
         "brand",
         "videoId",
         "videoSource",
         "duration",
         "taxonomy",
         "includeTerms",
         "excludeTerms",
         "media",
         "credit",
         "caption",
         "description",
         "videoCaptions",
         "franchiseId",
         "showAirTime",
         "slateImage",
         "mainImage",
         "thumbnailImage",
         "showTitle",
         "status",
         "pubstatus"
      ]
   },
   "query":{
      "bool":{
         "must":[
            {
               "query_string":{
                  "query":"langcode:\"en\""
               }
            },
            {
               "bool":{
                  "must_not":{
                     "query_string":{
                        "query":"(taxonomy.freeform.value:\"sociosqu\" AND taxonomy.freeform.value:\"nullam\") OR (taxonomy.games.id:\"sociosqu\" AND taxonomy.games.id:\"nullam\") OR (taxonomy.players.id:\"sociosqu\" AND taxonomy.players.id:\"nullam\") OR (taxonomy.teams.id:\"sociosqu\" AND taxonomy.teams.id:\"nullam\") OR (taxonomy.writer.value:\"sociosqu\" AND taxonomy.writer.value:\"nullam\") OR (taxonomy.channels.value:\"sociosqu\" AND taxonomy.channels.value:\"nullam\") OR (taxonomy.section.value:\"sociosqu\" AND taxonomy.section.value:\"nullam\") "
                     }
                  }
               }
            }
         ]
      }
   },
   "sort":[
      {
         "publishedUtc":{
            "order":"desc"
         }
      },
      {
         "_score":{
            "order":"desc"
         }
      }
   ]
}

1 Ответ

0 голосов
/ 30 ноября 2018

Я предполагаю, что у вас есть сопоставление что-то похожее на это:

{
  "mappings": {
    "_doc": {
      "properties": {
        "taxonomy": {
          "properties": {
            "game": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            },
            "team": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        }
      }
    }
  }
}

Требуемый запрос будет:

{
  "query": {
    "bool": {
      "filter": [
        {
          "query_string": {
            "query": "(t1 OR t2) NOT (t1 AND t2)",
            "fields": [
              "taxonomy.game.keyword",
              "taxonomy.team.keyword"
            ]
          }
        }
      ]
    }
  }
}

На основе документа, который вы предоставили, ваш список полей будетбыть:

"fields":[
    "taxonomy.teams.id",
    "taxonomy.freeform.value",
    "taxonomy.games.id",
    "taxonomy.players.id",
    "taxonomy.writer.value",
    "taxonomy.coaches.value"
    ]

Обратите внимание, что я предположил, id, value типа keyword.Если это не так, пожалуйста, измените отображение.Кроме того, если отображение создается динамически, то в подполе keyword в id, value будет отображаться имя подполя, аналогично тому, которое я использовал в примере отображения, в котором поле keyword указано в game иteam.

Вышеуказанное работает для эластичного поиска 6.x

Обновление на основе запроса, добавленного к вопросу:

Часть must_not вВаш запрос должен быть логически:

(f1=t1 AND f1=t2) OR (f2=t1 AND f2=t2) OR (f3=t1 AND f3=t2) ....

, где f i представляет поле и t i представляет термин.

Таким образом, must_not часть должна быть:

{
  "must_not": {
    "query_string": {
      "query": "(taxonomy.freeform.value:\"sociosqu\" AND taxonomy.freeform.value:\"nullam\") OR (taxonomy.games.id:\"sociosqu\" AND taxonomy.games.id:\"nullam\") OR (taxonomy.players.id:\"sociosqu\" AND taxonomy.players.id:\"nullam\") OR (taxonomy.teams.id:\"sociosqu\" AND taxonomy.teams.id:\"nullam\") OR (taxonomy.writer.value:\"sociosqu\" AND taxonomy.writer.value:\"nullam\") OR (taxonomy.channels.value:\"sociosqu\" AND taxonomy.channels.value:\"nullam\") OR (taxonomy.section.value:\"sociosqu\" AND taxonomy.section.value:\"nullam\") "
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...