similarity.asciidoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. [[index-modules-similarity]]
  2. == Similarity module
  3. A similarity (scoring / ranking model) defines how matching documents
  4. are scored. Similarity is per field, meaning that via the mapping one
  5. can define a different similarity per field.
  6. Configuring a custom similarity is considered an expert feature and the
  7. builtin similarities are most likely sufficient as is described in
  8. <<similarity>>.
  9. [float]
  10. [[configuration]]
  11. === Configuring a similarity
  12. Most existing or custom Similarities have configuration options which
  13. can be configured via the index settings as shown below. The index
  14. options can be provided when creating an index or updating index
  15. settings.
  16. [source,js]
  17. --------------------------------------------------
  18. PUT /index
  19. {
  20. "settings" : {
  21. "index" : {
  22. "similarity" : {
  23. "my_similarity" : {
  24. "type" : "DFR",
  25. "basic_model" : "g",
  26. "after_effect" : "l",
  27. "normalization" : "h2",
  28. "normalization.h2.c" : "3.0"
  29. }
  30. }
  31. }
  32. }
  33. }
  34. --------------------------------------------------
  35. // CONSOLE
  36. Here we configure the DFRSimilarity so it can be referenced as
  37. `my_similarity` in mappings as is illustrate in the below example:
  38. [source,js]
  39. --------------------------------------------------
  40. PUT /index/_mapping
  41. {
  42. "properties" : {
  43. "title" : { "type" : "text", "similarity" : "my_similarity" }
  44. }
  45. }
  46. --------------------------------------------------
  47. // CONSOLE
  48. // TEST[continued]
  49. [float]
  50. === Available similarities
  51. [float]
  52. [[bm25]]
  53. ==== BM25 similarity (*default*)
  54. TF/IDF based similarity that has built-in tf normalization and
  55. is supposed to work better for short fields (like names). See
  56. http://en.wikipedia.org/wiki/Okapi_BM25[Okapi_BM25] for more details.
  57. This similarity has the following options:
  58. [horizontal]
  59. `k1`::
  60. Controls non-linear term frequency normalization
  61. (saturation). The default value is `1.2`.
  62. `b`::
  63. Controls to what degree document length normalizes tf values.
  64. The default value is `0.75`.
  65. `discount_overlaps`::
  66. Determines whether overlap tokens (Tokens with
  67. 0 position increment) are ignored when computing norm. By default this
  68. is true, meaning overlap tokens do not count when computing norms.
  69. Type name: `BM25`
  70. [float]
  71. [[dfr]]
  72. ==== DFR similarity
  73. Similarity that implements the
  74. {lucene-core-javadoc}/org/apache/lucene/search/similarities/DFRSimilarity.html[divergence
  75. from randomness] framework. This similarity has the following options:
  76. [horizontal]
  77. `basic_model`::
  78. Possible values: {lucene-core-javadoc}/org/apache/lucene/search/similarities/BasicModelG.html[`g`],
  79. {lucene-core-javadoc}/org/apache/lucene/search/similarities/BasicModelIF.html[`if`],
  80. {lucene-core-javadoc}/org/apache/lucene/search/similarities/BasicModelIn.html[`in`] and
  81. {lucene-core-javadoc}/org/apache/lucene/search/similarities/BasicModelIne.html[`ine`].
  82. `after_effect`::
  83. Possible values: {lucene-core-javadoc}/org/apache/lucene/search/similarities/AfterEffectB.html[`b`] and
  84. {lucene-core-javadoc}/org/apache/lucene/search/similarities/AfterEffectB.html[`l`].
  85. `normalization`::
  86. Possible values: {lucene-core-javadoc}/org/apache/lucene/search/similarities/Normalization.NoNormalization.html[`no`],
  87. {lucene-core-javadoc}/org/apache/lucene/search/similarities/NormalizationH1.html[`h1`],
  88. {lucene-core-javadoc}/org/apache/lucene/search/similarities/NormalizationH2.html[`h2`],
  89. {lucene-core-javadoc}/org/apache/lucene/search/similarities/NormalizationH1.html[`h3`] and
  90. {lucene-core-javadoc}/org/apache/lucene/search/similarities/NormalizationZ.html[`z`].
  91. All options but the first option need a normalization value.
  92. Type name: `DFR`
  93. [float]
  94. [[dfi]]
  95. ==== DFI similarity
  96. Similarity that implements the http://trec.nist.gov/pubs/trec21/papers/irra.web.nb.pdf[divergence from independence]
  97. model.
  98. This similarity has the following options:
  99. [horizontal]
  100. `independence_measure`:: Possible values
  101. {lucene-core-javadoc}/org/apache/lucene/search/similarities/IndependenceStandardized.html[`standardized`],
  102. {lucene-core-javadoc}/org/apache/lucene/search/similarities/IndependenceSaturated.html[`saturated`],
  103. {lucene-core-javadoc}/org/apache/lucene/search/similarities/IndependenceChiSquared.html[`chisquared`].
  104. When using this similarity, it is highly recommended to remove stop words to get
  105. good relevance. Also beware that terms whose frequency is less than the expected
  106. frequency will get a score equal to 0.
  107. Type name: `DFI`
  108. [float]
  109. [[ib]]
  110. ==== IB similarity.
  111. {lucene-core-javadoc}/org/apache/lucene/search/similarities/IBSimilarity.html[Information
  112. based model] . The algorithm is based on the concept that the information content in any symbolic 'distribution'
  113. sequence is primarily determined by the repetitive usage of its basic elements.
  114. For written texts this challenge would correspond to comparing the writing styles of different authors.
  115. This similarity has the following options:
  116. [horizontal]
  117. `distribution`:: Possible values:
  118. {lucene-core-javadoc}/org/apache/lucene/search/similarities/DistributionLL.html[`ll`] and
  119. {lucene-core-javadoc}/org/apache/lucene/search/similarities/DistributionSPL.html[`spl`].
  120. `lambda`:: Possible values:
  121. {lucene-core-javadoc}/org/apache/lucene/search/similarities/LambdaDF.html[`df`] and
  122. {lucene-core-javadoc}/org/apache/lucene/search/similarities/LambdaTTF.html[`ttf`].
  123. `normalization`:: Same as in `DFR` similarity.
  124. Type name: `IB`
  125. [float]
  126. [[lm_dirichlet]]
  127. ==== LM Dirichlet similarity.
  128. {lucene-core-javadoc}/org/apache/lucene/search/similarities/LMDirichletSimilarity.html[LM
  129. Dirichlet similarity] . This similarity has the following options:
  130. [horizontal]
  131. `mu`:: Default to `2000`.
  132. The scoring formula in the paper assigns negative scores to terms that have
  133. fewer occurrences than predicted by the language model, which is illegal to
  134. Lucene, so such terms get a score of 0.
  135. Type name: `LMDirichlet`
  136. [float]
  137. [[lm_jelinek_mercer]]
  138. ==== LM Jelinek Mercer similarity.
  139. {lucene-core-javadoc}/core/org/apache/lucene/search/similarities/LMJelinekMercerSimilarity.html[LM
  140. Jelinek Mercer similarity] . The algorithm attempts to capture important patterns in the text, while leaving out noise. This similarity has the following options:
  141. [horizontal]
  142. `lambda`:: The optimal value depends on both the collection and the query. The optimal value is around `0.1`
  143. for title queries and `0.7` for long queries. Default to `0.1`. When value approaches `0`, documents that match more query terms will be ranked higher than those that match fewer terms.
  144. Type name: `LMJelinekMercer`
  145. [float]
  146. [[scripted_similarity]]
  147. ==== Scripted similarity
  148. A similarity that allows you to use a script in order to specify how scores
  149. should be computed. For instance, the below example shows how to reimplement
  150. TF-IDF:
  151. [source,js]
  152. --------------------------------------------------
  153. PUT /index
  154. {
  155. "settings": {
  156. "number_of_shards": 1,
  157. "similarity": {
  158. "scripted_tfidf": {
  159. "type": "scripted",
  160. "script": {
  161. "source": "double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;"
  162. }
  163. }
  164. }
  165. },
  166. "mappings": {
  167. "properties": {
  168. "field": {
  169. "type": "text",
  170. "similarity": "scripted_tfidf"
  171. }
  172. }
  173. }
  174. }
  175. PUT /index/_doc/1
  176. {
  177. "field": "foo bar foo"
  178. }
  179. PUT /index/_doc/2
  180. {
  181. "field": "bar baz"
  182. }
  183. POST /index/_refresh
  184. GET /index/_search?explain=true
  185. {
  186. "query": {
  187. "query_string": {
  188. "query": "foo^1.7",
  189. "default_field": "field"
  190. }
  191. }
  192. }
  193. --------------------------------------------------
  194. // CONSOLE
  195. Which yields:
  196. [source,js]
  197. --------------------------------------------------
  198. {
  199. "took": 12,
  200. "timed_out": false,
  201. "_shards": {
  202. "total": 1,
  203. "successful": 1,
  204. "skipped": 0,
  205. "failed": 0
  206. },
  207. "hits": {
  208. "total": {
  209. "value": 1,
  210. "relation": "eq"
  211. },
  212. "max_score": 1.9508477,
  213. "hits": [
  214. {
  215. "_shard": "[index][0]",
  216. "_node": "OzrdjxNtQGaqs4DmioFw9A",
  217. "_index": "index",
  218. "_type": "_doc",
  219. "_id": "1",
  220. "_score": 1.9508477,
  221. "_source": {
  222. "field": "foo bar foo"
  223. },
  224. "_explanation": {
  225. "value": 1.9508477,
  226. "description": "weight(field:foo in 0) [PerFieldSimilarity], result of:",
  227. "details": [
  228. {
  229. "value": 1.9508477,
  230. "description": "score from ScriptedSimilarity(weightScript=[null], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; double norm = 1/Math.sqrt(doc.length); return query.boost * tf * idf * norm;', options={}, params={}}]) computed from:",
  231. "details": [
  232. {
  233. "value": 1.0,
  234. "description": "weight",
  235. "details": []
  236. },
  237. {
  238. "value": 1.7,
  239. "description": "query.boost",
  240. "details": []
  241. },
  242. {
  243. "value": 2,
  244. "description": "field.docCount",
  245. "details": []
  246. },
  247. {
  248. "value": 4,
  249. "description": "field.sumDocFreq",
  250. "details": []
  251. },
  252. {
  253. "value": 5,
  254. "description": "field.sumTotalTermFreq",
  255. "details": []
  256. },
  257. {
  258. "value": 1,
  259. "description": "term.docFreq",
  260. "details": []
  261. },
  262. {
  263. "value": 2,
  264. "description": "term.totalTermFreq",
  265. "details": []
  266. },
  267. {
  268. "value": 2.0,
  269. "description": "doc.freq",
  270. "details": []
  271. },
  272. {
  273. "value": 3,
  274. "description": "doc.length",
  275. "details": []
  276. }
  277. ]
  278. }
  279. ]
  280. }
  281. }
  282. ]
  283. }
  284. }
  285. --------------------------------------------------
  286. // TESTRESPONSE[s/"took": 12/"took" : $body.took/]
  287. // TESTRESPONSE[s/OzrdjxNtQGaqs4DmioFw9A/$body.hits.hits.0._node/]
  288. WARNING: While scripted similarities provide a lot of flexibility, there is
  289. a set of rules that they need to satisfy. Failing to do so could make
  290. Elasticsearch silently return wrong top hits or fail with internal errors at
  291. search time:
  292. - Returned scores must be positive.
  293. - All other variables remaining equal, scores must not decrease when
  294. `doc.freq` increases.
  295. - All other variables remaining equal, scores must not increase when
  296. `doc.length` increases.
  297. You might have noticed that a significant part of the above script depends on
  298. statistics that are the same for every document. It is possible to make the
  299. above slightly more efficient by providing an `weight_script` which will
  300. compute the document-independent part of the score and will be available
  301. under the `weight` variable. When no `weight_script` is provided, `weight`
  302. is equal to `1`. The `weight_script` has access to the same variables as
  303. the `script` except `doc` since it is supposed to compute a
  304. document-independent contribution to the score.
  305. The below configuration will give the same tf-idf scores but is slightly
  306. more efficient:
  307. [source,js]
  308. --------------------------------------------------
  309. PUT /index
  310. {
  311. "settings": {
  312. "number_of_shards": 1,
  313. "similarity": {
  314. "scripted_tfidf": {
  315. "type": "scripted",
  316. "weight_script": {
  317. "source": "double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;"
  318. },
  319. "script": {
  320. "source": "double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;"
  321. }
  322. }
  323. }
  324. },
  325. "mappings": {
  326. "properties": {
  327. "field": {
  328. "type": "text",
  329. "similarity": "scripted_tfidf"
  330. }
  331. }
  332. }
  333. }
  334. --------------------------------------------------
  335. // CONSOLE
  336. ////////////////////
  337. [source,js]
  338. --------------------------------------------------
  339. PUT /index/_doc/1
  340. {
  341. "field": "foo bar foo"
  342. }
  343. PUT /index/_doc/2
  344. {
  345. "field": "bar baz"
  346. }
  347. POST /index/_refresh
  348. GET /index/_search?explain=true
  349. {
  350. "query": {
  351. "query_string": {
  352. "query": "foo^1.7",
  353. "default_field": "field"
  354. }
  355. }
  356. }
  357. --------------------------------------------------
  358. // CONSOLE
  359. // TEST[continued]
  360. [source,js]
  361. --------------------------------------------------
  362. {
  363. "took": 1,
  364. "timed_out": false,
  365. "_shards": {
  366. "total": 1,
  367. "successful": 1,
  368. "skipped": 0,
  369. "failed": 0
  370. },
  371. "hits": {
  372. "total": {
  373. "value": 1,
  374. "relation": "eq"
  375. },
  376. "max_score": 1.9508477,
  377. "hits": [
  378. {
  379. "_shard": "[index][0]",
  380. "_node": "OzrdjxNtQGaqs4DmioFw9A",
  381. "_index": "index",
  382. "_type": "_doc",
  383. "_id": "1",
  384. "_score": 1.9508477,
  385. "_source": {
  386. "field": "foo bar foo"
  387. },
  388. "_explanation": {
  389. "value": 1.9508477,
  390. "description": "weight(field:foo in 0) [PerFieldSimilarity], result of:",
  391. "details": [
  392. {
  393. "value": 1.9508477,
  394. "description": "score from ScriptedSimilarity(weightScript=[Script{type=inline, lang='painless', idOrCode='double idf = Math.log((field.docCount+1.0)/(term.docFreq+1.0)) + 1.0; return query.boost * idf;', options={}, params={}}], script=[Script{type=inline, lang='painless', idOrCode='double tf = Math.sqrt(doc.freq); double norm = 1/Math.sqrt(doc.length); return weight * tf * norm;', options={}, params={}}]) computed from:",
  395. "details": [
  396. {
  397. "value": 2.3892908,
  398. "description": "weight",
  399. "details": []
  400. },
  401. {
  402. "value": 1.7,
  403. "description": "query.boost",
  404. "details": []
  405. },
  406. {
  407. "value": 2,
  408. "description": "field.docCount",
  409. "details": []
  410. },
  411. {
  412. "value": 4,
  413. "description": "field.sumDocFreq",
  414. "details": []
  415. },
  416. {
  417. "value": 5,
  418. "description": "field.sumTotalTermFreq",
  419. "details": []
  420. },
  421. {
  422. "value": 1,
  423. "description": "term.docFreq",
  424. "details": []
  425. },
  426. {
  427. "value": 2,
  428. "description": "term.totalTermFreq",
  429. "details": []
  430. },
  431. {
  432. "value": 2.0,
  433. "description": "doc.freq",
  434. "details": []
  435. },
  436. {
  437. "value": 3,
  438. "description": "doc.length",
  439. "details": []
  440. }
  441. ]
  442. }
  443. ]
  444. }
  445. }
  446. ]
  447. }
  448. }
  449. --------------------------------------------------
  450. // TESTRESPONSE[s/"took": 1/"took" : $body.took/]
  451. // TESTRESPONSE[s/OzrdjxNtQGaqs4DmioFw9A/$body.hits.hits.0._node/]
  452. ////////////////////
  453. Type name: `scripted`
  454. [float]
  455. [[default-base]]
  456. ==== Default Similarity
  457. By default, Elasticsearch will use whatever similarity is configured as
  458. `default`.
  459. You can change the default similarity for all fields in an index when
  460. it is <<indices-create-index,created>>:
  461. [source,js]
  462. --------------------------------------------------
  463. PUT /index
  464. {
  465. "settings": {
  466. "index": {
  467. "similarity": {
  468. "default": {
  469. "type": "boolean"
  470. }
  471. }
  472. }
  473. }
  474. }
  475. --------------------------------------------------
  476. // CONSOLE
  477. If you want to change the default similarity after creating the index
  478. you must <<indices-open-close,close>> your index, send the following
  479. request and <<indices-open-close,open>> it again afterwards:
  480. [source,js]
  481. --------------------------------------------------
  482. POST /index/_close
  483. PUT /index/_settings
  484. {
  485. "index": {
  486. "similarity": {
  487. "default": {
  488. "type": "boolean"
  489. }
  490. }
  491. }
  492. }
  493. POST /index/_open
  494. --------------------------------------------------
  495. // CONSOLE
  496. // TEST[continued]