Melakukan Query Pencarian, Suggest, dan Highlight di Elasticsearch

Muhammad Arslan 26 Desember 2016

Melakukan Query Pencarian, Suggest, dan Highlight di Elasticsearch

Masih berkutat dengan Elasticsearch, kita akan mencoba beberapa query yang dapat digunakan untuk melalukan pencarian yang lebih detail. Kita akan mempelajari bagaimana melakukan bool query, highlighting, dan suggestion untuk meningkatkan hasil pencarian yang lebih efektif dan relevan. Selain itu kamu juga dapat melakukan pencarian melalui URI bila tidak menginginkan request body search.

Mari kita nikmati query - query ini :D.

0. Persiapan contoh data

Silahkan unduh superhero-mapping.json dan superhero.json yang ada di tautan berikut link menuju superhero.zip. Kemudian silahkan pasang elasticdump melalui NPM dan jalankan perintah berikut untuk memasang indeks dan contoh data di Elasticsearch.
$ npm install elasticdump -g
$ elasticdump --input=superhero-mapping.json --output=http://localhost:9200/demo --type=mapping
$ elasticdump --input=superhero.json --output=http://localhost:9200/demo/superhero --type=data
$ 

1. Mencari semua dokumen yang cocok

Berikut ini adalah contoh query yang akan menampilkan dokumen manapun sebanyak 20 dokumen. Agar lebih mudah digunakan, kamu dapat menampungnya di dalam file .json dan kita namai saja query.json. Nantinya file ini akan ditimpa dengan query baru, karena cukup sulit melewatkan request body melalui console atau terminal.
{
    "from":0,
    "size":20,
    "query":{
        "match_all":{}
    }
}
Sekarang coba eksekusi query diatas dengan menggunakan Curl:
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 26,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 149,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "14",
        "_score" : 1.0,
        "_source" : {
          "name" : "Punisher",
          "summary" : "The Punisher is a fictional character, an antihero that appears in comic books published by Marvel Comics. The character was created by writer Gerry Conway and artists John Romita, Sr., and Ross Andru, with publisher Stan Lee providing the name. The Punisher made his first appearance in The Amazing Spider-Man #129.\nThe Punisher is a vigilante who employs murder, kidnapping, extortion, coercion, threats of violence, and torture in his war on crime. Driven by the deaths of his wife and two children, who were killed by the mob during a shootout in New York Citys Central Park, the Punisher wages a one-man war on the mob and all criminals in general by using all manner of conventional war weaponry. His familys killers were the first to be slain. A war veteran of the U.S. military, Frank Castle is a master of martial arts, stealth tactics, guerrilla warfare, and a wide variety of weapons.\nThe Punishers brutal nature and willingness to kill made him a novel character in mainstream American comic books in 1974. By the late 1980s, he was part of a wave of psychologically troubled antiheroes and was featured in several monthly publications, including The Punisher War Journal, The Punisher War Zone, and The Punisher Armory. Despite his violent actions and dark nature, the Punisher has enjoyed some mainstream success on television, making guest appearances on Spider-Man: The Animated Series and even The Super Hero Squad Show. In feature films, Dolph Lundgren portrayed the Punisher in 1989, as did Thomas Jane in 2004, and Ray Stevenson in 2008."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "19",
        "_score" : 1.0,
        "_source" : {
          "name" : "Hellboy",
          "summary" : "Hellboy is a fictional character, a comic book superhero created by writer-artist Mike Mignola. The character first appeared in San Diego Comic-Con Comics #2, and has since appeared in various eponymous miniseries, one-shots and intercompany crossovers. The character has been adapted into two live-action feature films in 2004 and 2008 that starred Ron Perlman in the title role, and two straight-to-DVD animated films, as well as two video games – Asylum Seeker and The Science of Evil.\nA well-meaning demon whose true name is Anung Un Rama, Hellboy was summoned from Hell to Earth as an infant on December 23, 1944 by Nazi occultists. He was discovered by the Allied Forces; amongst them, Professor Trevor Bruttenholm, who formed the United States Bureau for Paranormal Research and Defense. In time Hellboy grew to be a large, red-skinned demon with a tail, horns, cloven hooves for feet, and an oversized right hand made of stone. He has been described as smelling of dry-roasted peanuts. Although a bit gruff, he shows none of the malevolence thought to be intrinsic to demons, has a strong sense of humor and works with other strange creatures in the BPRD. This is said to be because of his upbringing under Professor Bruttenholm, who raised him as a normal boy."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "22",
        "_score" : 1.0,
        "_source" : {
          "name" : "Doctor Strange",
          "summary" : "Doctor Stephen Vincent Strange is a fictional superhero who appears in comic books published by Marvel Comics. Doctor Strange is a former neurosurgeon, a practicing sorcerer, and serves as the Sorcerer Supreme, the primary protector of Earth against magical and mystical threats. Debuting in the Silver Age of comics, the character has featured in several self-titled series and Marvel-endorsed products including arcade and video games; animated television series; a direct-to-DVD film; and merchandise such as trading cards."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "24",
        "_score" : 1.0,
        "_source" : {
          "name" : "Scrooge McDuck",
          "summary" : "Scrooge McDuck is a cartoon character created in 1947 by Carl Barks and licensed by The Walt Disney Company. Scrooge is an elderly Scottish anthropomorphic white duck with a yellow-orange bill, legs, and feet. He typically wears a red or blue frock coat, top hat, pince-nez glasses, and spats and is portrayed in animations as speaking with a slight Scottish accent, also sometimes known as a Scottish burr. His dominant character trait is his thrift, and within the context of the fictional Disney universe, he is the Worlds richest person.\nNamed after Ebenezer Scrooge from the 1843 novel A Christmas Carol, Scrooge is a wealthy Scottish business magnate and tycoon. He was in his first few appearances characterized as a greedy miser and antihero, but in later comics and animated shorts and the modern day he is more often portrayed as a charitable and thrifty hero, adventurer, explorer and philanthropist. Scrooge was created by Barks as a comic book character originally as an antagonist for Donald Duck, first appearing in the 1947 Four Color story Christmas on Bear Mountain. The character soon became so popular that McDuck became a major figure of the Duck universe. In 1952 he was given his own comic book series, called Uncle Scrooge, which still runs today. Scrooge was most famously drawn by his creator Carl Barks, and later by Don Rosa. Comics have remained Scrooges primary medium, although he has also appeared in animated cartoons, most extensively in the television series Duck Tales."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "25",
        "_score" : 1.0,
        "_source" : {
          "name" : "Nick Fury",
          "summary" : "Colonel Nicholas Joseph Nick Fury is a fictional World War II army hero and present-day super-spy in the Marvel Comics Universe. Created by artist Jack Kirby and writer Stan Lee, Fury first appeared in Sgt. Fury and his Howling Commandos #1, a World War II combat series that portrayed the cigar-chomping Fury as leader of an elite U.S. Army unit.\nThe modern-day Fury, initially a CIA agent, debuted a few months later in Fantastic Four #21. In Strange Tales #135, the character transformed into a James Bond-like spy and leading agent of the fictional espionage agency S.H.I.E.L.D. The character makes frequent appearances in Marvel comic books as the former head of S.H.I.E.L.D. and as an intermediary between the U.S. government or the United Nations and various superheroes. It is eventually revealed that Fury takes a special medication called the Infinity Formula that halted his aging and allows him to be active despite being nearly a century old.\nNick Fury appears in several Marvel comic series set in alternate universes, as well as multiple animated films, television shows, and video games based on the comics. The character is portrayed by David Hasselhoff in the 1998 television movie Nick Fury: Agent of S.H.I.E.L.D. and by Samuel L. Jackson in the 2008 film Iron Man, its 2010 sequel Iron Man 2, the 2011 films Thor and Captain America: The First Avenger, and the 2012 film The Avengers; the first five films of a nine-film commitment as the character for the Marvel Cinematic Universe franchise. The Ultimate Marvel version of the character was based on Jacksons appearance and screen persona, well before he was cast in the role. In 2011, Nick Fury was ranked 33rd in IGNs Top 100 Comic Book Heroes."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "26",
        "_score" : 1.0,
        "_source" : {
          "name" : "Silver Surfer",
          "summary" : "The Silver Surfer is a fictional character, a superhero appearing in comic books and other publications by Marvel Comics. Originally a young astronomer named Norrin Radd on the planet Zenn-La, he saved his homeworld from the planet devourer, Galactus, by serving as his herald. Imbued in return with a tiny portion of Galactuss Power Cosmic, Radd acquired vast power, a new body and a surfboard-like craft on which he could travel faster than light. Now known as the Silver Surfer, Radd roamed the cosmos searching for planets for Galactus to consume. When his travels took him to Earth, he met the Fantastic Four, a team of powerful superheroes who helped him rediscover his humanity and nobility of spirit. Betraying Galactus, the Surfer saved Earth but was exiled there as punishment. In 2011, IGN ranked Silver Surfer 41st in its Top 100 Comic Heroes list."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "29",
        "_score" : 1.0,
        "_source" : {
          "name" : "Deathstroke",
          "summary" : "Deathstroke the Terminator is a fictional comic book supervillain, and sometimes antihero, who appears in books published by DC Comics. Created by writer Marv Wolfman and artist George Pérez, he is a mercenary and assassin who first appeared in The New Teen Titans #2. Wizard Magazine rated him the 84th greatest villain of all time and the 72nd greatest comic book character of all time. Also, in 2009, Deathstroke was ranked as IGNs 32nd greatest comic book villain of all time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "40",
        "_score" : 1.0,
        "_source" : {
          "name" : "Supergirl",
          "summary" : "Supergirl is a female counterpart to Superman. As his cousin, she shares his super powers and vulnerability to Kryptonite. She was created by writer Otto Binder and designed by artist Al Plastino in 1959. She first appeared in the Action Comics comic book series and later branched out into animation, film, television, and merchandising. In May 2011, Supergirl placed 94th on IGNs list of the Top 100 Comic Book Heroes of All Time.\nSupergirl plays a supporting role in various DC Comics publications, including Action Comics, Superman, and several comic book series unrelated to Superman. In 1969, Supergirls adventures became the lead feature in Adventure Comics, and she later starred in an eponymous comic book series which debuted in 1972 and ran until 1974, followed by a second monthly comic book series titled The Daring New Adventures of Supergirl, which ran from 1982 to 1984.\nSupergirl dies in the 1985 limited series Crisis on Infinite Earths, and DC Comics subsequently rebooted the continuity of the DC Comics Universe, reestablishing Supermans character as the sole survivor of Kryptons destruction. Following the conclusion of Crisis on Infinite Earths, several different characters written as having no familial relationship to Superman have assumed the role of Supergirl, including Matrix, Linda Danvers, and Cir-El. Following the cancellation of the third Supergirl comic book series, starring the Linda Danvers version of the character, a modern version of Kara Zor-El was reintroduced into the DC Comics continuity in issue #8 of the Superman/Batman comic book series titled The Supergirl from Krypton. The modern Kara Zor-El stars as Supergirl in an eponymous comic book series, in addition to playing a supporting role in various other DC Comics publications."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "41",
        "_score" : 1.0,
        "_source" : {
          "name" : "Mystique",
          "summary" : "Mystique is a fictional character associated with the Marvel Comics franchise X-Men. Created by artist David Cockrum and writer Chris Claremont, she first appeared in Ms. Marvel #16.\nThroughout most of her history, Mystique has been a supervillain, founding her own Brotherhood of Mutants and assassinating several important people involved in mutant affairs. Mystique herself is a mutant, a shapeshifter whose natural appearance includes blue skin and yellow eyes. At one point, she mentions that she is over 100 years old. Mystique is the mother of the villain Graydon Creed, the X-Men hero Nightcrawler, and adoptive mother of the heroine Rogue. She is forced to abandon Nightcrawler, but raises Rogue for a number of years, and the two women have mixed feelings towards one another.\nDespite Mystiques history of crime, she works with the X-Mens Professor X in a short-lived series. She is later voted straight into the X-Men.\nActress Rebecca Romijn portrayed Mystique in the first three of the X-Men films. In the 2011 film, X-Men: First Class, Jennifer Lawrence plays the role of a young Mystique. Lawrence will reprise her role again in the upcoming 2014 sequel, X-Men: Days of Future Past. In 2009, Mystique was ranked as IGNs 18th Greatest Comic Book Villain of All Time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "44",
        "_score" : 1.0,
        "_source" : {
          "name" : "Riddler",
          "summary" : "The Riddler is a fictional character, a comic book supervillain appearing in comic books published by DC Comics. He usually appears as an enemy of Batman. Created by writer Bill Finger and artist Dick Sprang, the character first appeared in Detective Comics #140. In 2009, the Riddler was ranked as IGNs 59th Greatest Comic Book Villain of All Time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "48",
        "_score" : 1.0,
        "_source" : {
          "name" : "Nightcrawler",
          "summary" : "Nightcrawler is a fictional character, a comic book superhero in the Marvel Universe. He has been associated with both the X-Men and Excalibur, originally appearing in comic books published by Marvel Comics. Created by writer Len Wein and artist Dave Cockrum, he debuted in Giant-Size X-Men #1. During the X-Men: Second Coming storyline, Nightcrawler is killed in an attempt to save Hope Summers in X-Force #26.\nA mutant, Nightcrawler possesses superhuman agility, the ability to teleport across short or long distances in a puff of crimson red smoke, invisibility in deep shadows, and adhesive hands and feet. His physical mutations include indigo colored skin, two-toed feet and three-fingered hands, yellow eyes, pointed ears, and a prehensile tail. In Nightcrawlers earlier comic book appearances he is depicted as being a happy-go-lucky practical joker and teaser, and a fan of swashbuckling fiction. Nightcrawler is a German Catholic and while this is not emphasized as much in his earlier comic book appearances, in later depictions Nightcrawler is more vocal about his faith.\nSince his inception, Nightcrawler has had a regular presence in Marvel-related comic books and video games. He has featured in a small number of the 1990s X-Men animated series episodes and was a regular on its successors, X-Men: Evolution and Wolverine and the X-Men. In 2003, he was a major character in the film X2, and was portrayed by Alan Cumming."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "52",
        "_score" : 1.0,
        "_source" : {
          "name" : "The Green Hornet",
          "summary" : "The Green Hornet is an American radio and television masked vigilante created by George W. Trendle and Fran Striker, with input from radio director James Jewell, in 1936. Since his radio debut in the 1930s, the Green Hornet has appeared in numerous serialized dramas in a wide variety of media. The character appeared in film serials in the 1940s, a network television program in the 1960s, multiple comic book series from the 1940s on, and a feature film in January 2011.\nThough various incarnations sometimes change details, in most versions the Green Hornet is the alter ego of Britt Reid, wealthy young publisher of the Daily Sentinel newspaper by day, who goes out in his masked Green Hornet identity at night to fight crime as a vigilante. Reid is accompanied by his loyal and similarly masked partner and confidant, Kato, who drives their technologically advanced car, the Black Beauty. As the Green Hornet, Reid masquerades as a criminal to infiltrate the underworld, leaving behind criminals and any incriminating evidence found for the police."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "60",
        "_score" : 1.0,
        "_source" : {
          "name" : "Carnage",
          "summary" : "Carnage is a fictional comic book supervillain appearing in books published by Marvel Comics, usually as an enemy of Spider-Man. The character first appeared as Cletus Kasady in The Amazing Spider-Man #344 and as Carnage in The Amazing Spider-Man #360, and was created by writer David Michelinie and artist Mark Bagley, based on elements of the precursor character Venom. In 2009, Carnage was ranked as IGNs 90th Greatest Comic Book Villain of All Time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "73",
        "_score" : 1.0,
        "_source" : {
          "name" : "Henry Pym",
          "summary" : "Dr. Henry Hank Pym is a fictional character that appears in publications by Marvel Comics. Created by editor and plotter Stan Lee, scripter Larry Lieber and penciler Jack Kirby, the character first appeared in Tales to Astonish #27. Pyms character, a scientist that debuted in a standalone science-fiction anthology story, returned several issues later as the superhero Ant-Man, with the power to shrink to the size of an insect. Pym is eventually given a crime-fighting partner, Janet van Dyne and goes on to assume other superhero identities, including the size-changing Giant-Man and Goliath; the insect-themed Yellowjacket; and briefly the Wasp.\nDebuting in the Silver Age of Comic Books, the character of Henry Pym has featured in other Marvel-endorsed products such as animated films; arcade and video games; television series and merchandise such as action figures and trading cards."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "79",
        "_score" : 1.0,
        "_source" : {
          "name" : "Gwen Stacy",
          "summary" : "Gwen Maxine Stacy is a fictional comic character who appears in books published by Marvel Comics, usually as a supporting character in those featuring Spider-Man. Created by writer Stan Lee and artist Steve Ditko, she first appeared in The Amazing Spider-Man #31.\nA college student, Gwen was originally the first true love of Peter Parker before he developed deep feelings for her friend and rival, Mary Jane Watson. The Green Goblin caused Spider-Man to accidentally kill Gwen in The Amazing Spider-Man #121. Both the decision to kill Gwen and the method in which Marvel implemented it remain controversial among fans, but the death became a pivotal point in both Spider-Man’s history and in American comic books in general. Many point to Gwens death as the end of the Silver Age of Comics. Spider-Man writers and fans disagree about who is the character’s one true love: Gwen or his subsequent love interest, Mary Jane. The character was ranked 89th in Comics Buyers Guides 100 Sexiest Women in Comics list.\nBryce Dallas Howard appeared as the character in the 2007 film Spider-Man 3. Emma Stone portrays Gwen as Peter Parkers friend and love interest in the reboot film The Amazing Spider-Man."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "84",
        "_score" : 1.0,
        "_source" : {
          "name" : "Sentinel",
          "summary" : "Sentinels are a fictional variety of mutant-hunting robots, appearing in the Marvel Comics Universe. They are usually portrayed as antagonists to the X-Men. Created by Stan Lee and Jack Kirby, they first appeared in The X-Men #14.\nAccording to Marvel canon, Sentinels are programmed to locate mutants and capture or kill them. Though several types of Sentinels have been introduced, the typical Sentinel is three stories tall, capable of flight, projects energy blasts, and can detect mutants.\nThe Sentinels have been featured in several X-Men video games, and played a large role in the 1990s X-Men animated series. Additionally, a simulated version made a brief appearance in the beginning of the 2006 film, X-Men: The Last Stand. In 2009, the Sentinels were ranked by IGN as the 38th Greatest Comic Book Villain of All Time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "89",
        "_score" : 1.0,
        "_source" : {
          "name" : "Clark Kent",
          "summary" : "Clark Kent is an American fictional character created by Jerry Siegel and Joe Shuster. Appearing regularly in stories published by DC Comics, he debuted in Action Comics #1 and serves as the civilian and secret identity of the superhero Superman.\nOver the decades there has been considerable debate as to which personality the character identifies with most. From his first introduction in 1938 to the mid-1980s, Clark Kent was seen mostly as a disguise for Superman, enabling him to mix with ordinary people. This was the view in most comics and other media such as TV and radio. In 1986, during John Byrnes revamping of the character, the emphasis was on Superman being the manufactured persona of Clark Kent, the side of the character he most identifies with. Different takes persist in the present."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "92",
        "_score" : 1.0,
        "_source" : {
          "name" : "Superboy",
          "summary" : "Superboy is the name of several fictional characters that have been published by DC Comics, most of them youthful incarnations of Superman. These characters have also been the main characters of four ongoing Superboy comic book series published by DC.\nThe first, and arguably best-known, Superboy was simply Superman as a boy, acting as a superhero in Smallville, where Kal-El lives under his secret identity, Clark Kent. The character was featured in several series from the 1940s until the 1980s, with long runs appearing in Adventure Comics and two eponymous series, Superboy and The New Adventures of Superboy. He developed a mythos and supporting cast of his own, including foster parents Ma and Pa Kent, love interest Lana Lang, and time traveling allies the Legion of Super-Heroes.\nWhen DC Comics rewrote much of its continuity in 1986, Supermans history was changed so that he never took a costumed identity until adulthood, erasing Superboy from the canonical history of Superman, although many aspects of the backstory created in Superboy comics, such as Clarks friendship with Lana Lang, remained. In the last few years, some additional features of Superboys history, such as his tenure in the Legion, have also been reintroduced into the story of Supermans youth."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "98",
        "_score" : 1.0,
        "_source" : {
          "name" : "Adam Strange",
          "summary" : "Adam Strange is a fictional superhero published by DC Comics. Created by editor Julius Schwartz with a costume designed by Murphy Anderson, he first appeared in Showcase #17.\nIn May 2011, Adam Strange placed 97th on IGNs Top 100 Comic Book Heroes of All Time."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "99",
        "_score" : 1.0,
        "_source" : {
          "name" : "Flash",
          "summary" : "The Flash is a fictional character, a superhero in the DC Comics universe. He is the second character known as the Flash. The character first appeared in Showcase #4, created by writers Robert Kanigher and John Broome and penciler Carmine Infantino. His name combines talk show hosts Barry Gray and Steve Allen. His death in 1985 removed the character from the regular DC lineup for 23 years. His return to regular comics occurred in 2008 within the pages of Grant Morrisons Final Crisis limited series."
        }
      }
    ]
  }
}

2. Mencari sebagian dokumen yang cocok

Sekarang kita akan mencoba mencari beberapa dokumen yang mengandung kata "killing" pada field summary. Disini kita ganti "match_all" dengan "match" disertai dengan field yang akan dicocokkan.
{
    "from":0,
    "size":10,
    "query":{
        "match":{"summary":"killing"}
    }
}
Sekarang coba eksekusi query diatas dengan menggunakan Curl:
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 40,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 6,
    "max_score" : 3.7952158,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "145",
        "_score" : 3.7952158,
        "_source" : {
          "name" : "X-23",
          "summary" : "X-23 is a fictional comic book superheroine appearing in books published by Marvel Comics, in particular those featuring the X-Men. X-23 is a female clone of Wolverine.\nCloned from a damaged copy of Wolverines genome, X-23 was created to be the perfect killing machine. For years, she proved herself a notable assassin, though a series of tragedies eventually led her to Wolverine and the X-Men, with whom she now seeks to turn her life around."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "107",
        "_score" : 2.5077243,
        "_source" : {
          "name" : "Himura Kenshin",
          "summary" : "Himura Kenshin, known as Kenshin Himura in the English-language anime dubs, is a fictional character as well as the main protagonist from the Rurouni Kenshin manga created by Nobuhiro Watsuki, as well as the related media in the franchise. When creating Kenshin, Watsuki designed him to be the physical opposite of Hiko Seijūrō, a character that appears in Watsukis first one-shot manga, Crescent Moon in the Warring States; a character with the same name appears in Rurouni Kenshin as Kenshins swordsmanship teacher.\nKenshins story is set in a fictional version of Japan during the Meiji period. Kenshin is a former legendary assassin known as Hitokiri Battōsai, more properly named Himura Battōsai. At the end of the Bakumatsu, he becomes a wandering samurai, now wielding a sakabatō, a katana that has the cutting edge on the inwardly curved side of the sword, thus being nearly incapable of killing. Kenshin wanders the countryside of Japan offering protection and aid to those in need, as atonement for the murders he once committed as an assassin. In Tokyo, he meets a young woman named Kamiya Kaoru, who invites him to live in her dojo despite learning about Kenshins past. Throughout the series, Kenshin begins to establish lifelong relationships with many people, including ex-enemies, while dealing with his fair share of enemies, new and old. Through these encounters and relationships, Kenshin begins to find true atonement for his past enabling him to fully conquer his Battōsai nature."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "12",
        "_score" : 2.20746,
        "_source" : {
          "name" : "Lex Luthor",
          "summary" : "Alexander Joseph Lex Luthor is a fictional character, a supervillain appearing in comic books published by DC Comics. Luthor is the archenemy of Superman, and as a high-status supervillain, has also come into conflict with Batman and other superheroes in the DC Universe. Created by Jerry Siegel and Joe Shuster, the character first appeared in Action Comics #23. Luthor is described as a power-mad, evil scientist of high intelligence and incredible technological prowess. Luthors goals typically center on killing Superman, the foremost obstacle to achieving the villains megalomaniacal goals. Despite periodically wearing a powered exoskeleton, Luthor has traditionally lacked superpowers or a dual identity.\nThe character was originally depicted as a mad scientist who, in the vein of pulp novels, wreaks havoc on the world with his futuristic weaponry. In his earliest appearances, Luthor is shown with a full head of red hair. Despite this, the character later became hairless as the result of an artists mistake. A 1960 story by Jerry Siegel expanded upon Luthors origin and motivations, revealing him to be a childhood friend of Supermans who lost his hair when a fire destroyed his laboratory; Luthor vowed revenge."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "4",
        "_score" : 1.807942,
        "_source" : {
          "name" : "Wolverine",
          "summary" : "Wolverine is a fictional character, a superhero who appears in comic books published by Marvel Comics. Born James Howlett and commonly known as Logan, Wolverine is a mutant who possesses animal-keen senses, enhanced physical capabilities and a healing factor that allows him to recover from virtually any wound, disease, or toxin at an accelerated rate. The healing factor also slows down his aging process, enabling him to live beyond a normal human lifespan. His powerful healing factor enabled the supersoldier program Weapon X to bond the near-indestructible metal alloy adamantium to his skeleton without killing him. He is most often depicted as a member of the X-Men, Alpha Flight, or later the Avengers.\nThe character first appeared in the last panel of The Incredible Hulk #180 and was created by writer Len Wein and Marvel art director John Romita, Sr., who designed the character, and was first drawn for publication by Herb Trimpe. Wolverine later joined the X-Mens All New, All Different roster in Giant-Size X-Men #1. X-Men writer Chris Claremont played a significant role in the characters subsequent development, along with artist/writer John Byrne, who insisted on making the character older than the other X-Men. Artist Frank Miller collaborated with Claremont and helped to revise the character with a four-part eponymous limited series from September to December 1982 in which Wolverines catchphrase, Im the best there is at what I do, but what I do best isnt very nice, debuted."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "87",
        "_score" : 1.5891573,
        "_source" : {
          "name" : "Barbara Gordon",
          "summary" : "Barbara Gordon is a fictional character, a superheroine appearing in comic books published by DC Comics and in related media. The character was created by Gardner Fox and Carmine Infantino. At the request of the producers of the 1960s Batman television series, DC editor Julius Schwartz called for a new female counterpart to the superhero Batman that could be introduced into publication and the third season of the show simultaneously. The character subsequently made her first comic book appearance as Batgirl in Detective Comics No. 359 titled, The Million Dollar Debut of Batgirl! by writer Gardner Fox and artist Carmine Infantino. Written as the daughter of Gotham City police commissioner James Gordon, her civilian identity is given a doctorate in library science and she is employed as head of Gotham City Public Library, as well as later being elected to the United States Congress.\nIn addition to appearing in other DC publications, she receives her first starring role in Batman Family which debuted in 1975, partnered with the original Robin, Dick Grayson. In 1988, following the editorial retirement of the characters Batgirl persona in Barbara Kesels Batgirl Special No. 1, Alan Moores graphic novel Batman: The Killing Joke depicts the Joker shooting her through the spinal cord in her civilian identity, resulting in paraplegia. In subsequent stories, editor Kim Yale and writer John Ostrander establish the character as a computer expert and information broker known as Oracle. Providing intelligence and computer hacking services to assist other superheroes, she makes her first appearance as Oracle in Suicide Squad No. 23. She is featured in the one-shot comic Black Canary/Oracle: Birds of Prey written by Chuck Dixon, which later became the monthly title Birds of Prey starring both characters. The series depicts her as a great intellect uninhibited by her paralysis, skilled in the martial art of eskrima. Employing Black Canary as her partner and field agent, Oracle later operates as the leader of a full team of female crimefighters who engage in global espionage missions, under writer Gail Simone. In 2011, following a company wide relaunch of all DC Comics titles, the characters mobility is restored and she is given a starring role in the eponymous Batgirl monthly comic, as well as Birds of Prey, as part of The New 52."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "38",
        "_score" : 1.5565212,
        "_source" : {
          "name" : "Sasuke Uchiha",
          "summary" : "Sasuke Uchiha is a character of the Naruto manga and anime series created by Masashi Kishimoto. In the story, Sasuke is a member of the Uchiha clan, a highly skilled clan of ninjas allied to the village of Konohagakure. His primary motivation throughout the series is to avenge the destruction of his entire clan by killing his brother, Itachi Uchiha, a task he pursues at all costs. While he was initially cold and singularly driven by his revenge, he becomes more empathetic through his relationships with other characters, notably Naruto Uzumaki, whom he comes to consider as a rival. Sasuke has additionally appeared in several of the featured movies in the series, as well as several other media relating to the series, including several video games and OVAs.\nHe was created as a rival and foil to the series titular character, Naruto Uzumaki. Sasukes design caused difficulties for Kishimoto as he drew the manga scenes, but he has grown to enjoy drawing him. In the animated adaptations from the manga Sasuke has been voiced by Noriaki Sugiyama in Japanese and Yuri Lowenthal in the English dub.\nSeveral anime and manga publications have provided acclaim and criticism of Sasukes character. While many reviewers have noted his cold and detached attitude and abilities, he has been viewed as a stereotypical rival in the mold of several similar characters in other shōnen manga. The characters development has been praised with reviewers praising his rivalry with other appearing characters and the impact he makes in the plot overall. Moreover, Sasuke has been highly popular with the Naruto reader base, placing high in several popularity polls. Merchandise based on Sasuke has also been released, including action figures and plush dolls."
        }
      }
    ]
  }
}

Kamu juga dapat menambahkan pengurutan pada hasil pencarian sesuai skor agar lebih enak dibaca:

{
    "from":0,
    "size":10,
    "sort":[
        {"_score":"asc"}
    ],
    "query":{
        "match":{"summary":"killing"}
    }
}
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 15,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 6,
    "max_score" : null,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "38",
        "_score" : 1.5565212,
        "_source" : {
          "name" : "Sasuke Uchiha",
          "summary" : "Sasuke Uchiha is a character of the Naruto manga and anime series created by Masashi Kishimoto. In the story, Sasuke is a member of the Uchiha clan, a highly skilled clan of ninjas allied to the village of Konohagakure. His primary motivation throughout the series is to avenge the destruction of his entire clan by killing his brother, Itachi Uchiha, a task he pursues at all costs. While he was initially cold and singularly driven by his revenge, he becomes more empathetic through his relationships with other characters, notably Naruto Uzumaki, whom he comes to consider as a rival. Sasuke has additionally appeared in several of the featured movies in the series, as well as several other media relating to the series, including several video games and OVAs.\nHe was created as a rival and foil to the series titular character, Naruto Uzumaki. Sasukes design caused difficulties for Kishimoto as he drew the manga scenes, but he has grown to enjoy drawing him. In the animated adaptations from the manga Sasuke has been voiced by Noriaki Sugiyama in Japanese and Yuri Lowenthal in the English dub.\nSeveral anime and manga publications have provided acclaim and criticism of Sasukes character. While many reviewers have noted his cold and detached attitude and abilities, he has been viewed as a stereotypical rival in the mold of several similar characters in other shōnen manga. The characters development has been praised with reviewers praising his rivalry with other appearing characters and the impact he makes in the plot overall. Moreover, Sasuke has been highly popular with the Naruto reader base, placing high in several popularity polls. Merchandise based on Sasuke has also been released, including action figures and plush dolls."
        },
        "sort" : [
          1.5565212
        ]
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "87",
        "_score" : 1.5891573,
        "_source" : {
          "name" : "Barbara Gordon",
          "summary" : "Barbara Gordon is a fictional character, a superheroine appearing in comic books published by DC Comics and in related media. The character was created by Gardner Fox and Carmine Infantino. At the request of the producers of the 1960s Batman television series, DC editor Julius Schwartz called for a new female counterpart to the superhero Batman that could be introduced into publication and the third season of the show simultaneously. The character subsequently made her first comic book appearance as Batgirl in Detective Comics No. 359 titled, The Million Dollar Debut of Batgirl! by writer Gardner Fox and artist Carmine Infantino. Written as the daughter of Gotham City police commissioner James Gordon, her civilian identity is given a doctorate in library science and she is employed as head of Gotham City Public Library, as well as later being elected to the United States Congress.\nIn addition to appearing in other DC publications, she receives her first starring role in Batman Family which debuted in 1975, partnered with the original Robin, Dick Grayson. In 1988, following the editorial retirement of the characters Batgirl persona in Barbara Kesels Batgirl Special No. 1, Alan Moores graphic novel Batman: The Killing Joke depicts the Joker shooting her through the spinal cord in her civilian identity, resulting in paraplegia. In subsequent stories, editor Kim Yale and writer John Ostrander establish the character as a computer expert and information broker known as Oracle. Providing intelligence and computer hacking services to assist other superheroes, she makes her first appearance as Oracle in Suicide Squad No. 23. She is featured in the one-shot comic Black Canary/Oracle: Birds of Prey written by Chuck Dixon, which later became the monthly title Birds of Prey starring both characters. The series depicts her as a great intellect uninhibited by her paralysis, skilled in the martial art of eskrima. Employing Black Canary as her partner and field agent, Oracle later operates as the leader of a full team of female crimefighters who engage in global espionage missions, under writer Gail Simone. In 2011, following a company wide relaunch of all DC Comics titles, the characters mobility is restored and she is given a starring role in the eponymous Batgirl monthly comic, as well as Birds of Prey, as part of The New 52."
        },
        "sort" : [
          1.5891573
        ]
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "4",
        "_score" : 1.807942,
        "_source" : {
          "name" : "Wolverine",
          "summary" : "Wolverine is a fictional character, a superhero who appears in comic books published by Marvel Comics. Born James Howlett and commonly known as Logan, Wolverine is a mutant who possesses animal-keen senses, enhanced physical capabilities and a healing factor that allows him to recover from virtually any wound, disease, or toxin at an accelerated rate. The healing factor also slows down his aging process, enabling him to live beyond a normal human lifespan. His powerful healing factor enabled the supersoldier program Weapon X to bond the near-indestructible metal alloy adamantium to his skeleton without killing him. He is most often depicted as a member of the X-Men, Alpha Flight, or later the Avengers.\nThe character first appeared in the last panel of The Incredible Hulk #180 and was created by writer Len Wein and Marvel art director John Romita, Sr., who designed the character, and was first drawn for publication by Herb Trimpe. Wolverine later joined the X-Mens All New, All Different roster in Giant-Size X-Men #1. X-Men writer Chris Claremont played a significant role in the characters subsequent development, along with artist/writer John Byrne, who insisted on making the character older than the other X-Men. Artist Frank Miller collaborated with Claremont and helped to revise the character with a four-part eponymous limited series from September to December 1982 in which Wolverines catchphrase, Im the best there is at what I do, but what I do best isnt very nice, debuted."
        },
        "sort" : [
          1.807942
        ]
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "12",
        "_score" : 2.20746,
        "_source" : {
          "name" : "Lex Luthor",
          "summary" : "Alexander Joseph Lex Luthor is a fictional character, a supervillain appearing in comic books published by DC Comics. Luthor is the archenemy of Superman, and as a high-status supervillain, has also come into conflict with Batman and other superheroes in the DC Universe. Created by Jerry Siegel and Joe Shuster, the character first appeared in Action Comics #23. Luthor is described as a power-mad, evil scientist of high intelligence and incredible technological prowess. Luthors goals typically center on killing Superman, the foremost obstacle to achieving the villains megalomaniacal goals. Despite periodically wearing a powered exoskeleton, Luthor has traditionally lacked superpowers or a dual identity.\nThe character was originally depicted as a mad scientist who, in the vein of pulp novels, wreaks havoc on the world with his futuristic weaponry. In his earliest appearances, Luthor is shown with a full head of red hair. Despite this, the character later became hairless as the result of an artists mistake. A 1960 story by Jerry Siegel expanded upon Luthors origin and motivations, revealing him to be a childhood friend of Supermans who lost his hair when a fire destroyed his laboratory; Luthor vowed revenge."
        },
        "sort" : [
          2.20746
        ]
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "107",
        "_score" : 2.5077243,
        "_source" : {
          "name" : "Himura Kenshin",
          "summary" : "Himura Kenshin, known as Kenshin Himura in the English-language anime dubs, is a fictional character as well as the main protagonist from the Rurouni Kenshin manga created by Nobuhiro Watsuki, as well as the related media in the franchise. When creating Kenshin, Watsuki designed him to be the physical opposite of Hiko Seijūrō, a character that appears in Watsukis first one-shot manga, Crescent Moon in the Warring States; a character with the same name appears in Rurouni Kenshin as Kenshins swordsmanship teacher.\nKenshins story is set in a fictional version of Japan during the Meiji period. Kenshin is a former legendary assassin known as Hitokiri Battōsai, more properly named Himura Battōsai. At the end of the Bakumatsu, he becomes a wandering samurai, now wielding a sakabatō, a katana that has the cutting edge on the inwardly curved side of the sword, thus being nearly incapable of killing. Kenshin wanders the countryside of Japan offering protection and aid to those in need, as atonement for the murders he once committed as an assassin. In Tokyo, he meets a young woman named Kamiya Kaoru, who invites him to live in her dojo despite learning about Kenshins past. Throughout the series, Kenshin begins to establish lifelong relationships with many people, including ex-enemies, while dealing with his fair share of enemies, new and old. Through these encounters and relationships, Kenshin begins to find true atonement for his past enabling him to fully conquer his Battōsai nature."
        },
        "sort" : [
          2.5077243
        ]
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "145",
        "_score" : 3.7952158,
        "_source" : {
          "name" : "X-23",
          "summary" : "X-23 is a fictional comic book superheroine appearing in books published by Marvel Comics, in particular those featuring the X-Men. X-23 is a female clone of Wolverine.\nCloned from a damaged copy of Wolverines genome, X-23 was created to be the perfect killing machine. For years, she proved herself a notable assassin, though a series of tragedies eventually led her to Wolverine and the X-Men, with whom she now seeks to turn her life around."
        },
        "sort" : [
          3.7952158
        ]
      }
    ]
  }
}

3. Melakukan bool query

Sekarang mari kita coba melakukan query yang agak kompleks dengan memakai "must" dan "filter". Dimana query tersebut dapat kamu artikan sebagai "SELECT * FROM superhero WHERE name LIKE '%man%' AND summary LIKE '%fictional%' AND summary LIKE '%comic%'".
{
    "from":0,
    "size":10,
    "sort":[
        "_score"
    ],
    "query":{
        "bool":{
            "must":{
                "wildcard":{
                    "name":"*man*"
                }
            },
        "filter":[
            {"match":{"summary":"fictional"}},
            {"match":{"summary":"comic"}}
        ]
    }
}

}

Nah sekarang kita coba eksekusi query diatas:

$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 78,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 9,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "103",
        "_score" : 1.0,
        "_source" : {
          "name" : "Invisible Woman",
          "summary" : "Susan Sue Storm Richards is a fictional character, a superheroine that appears in comic books published by Marvel Comics. She was the first female superhero created by Marvel in the Silver Age of Comics. Like the other founding members of the Fantastic Four, Sue received her powers after being exposed to a cosmic storm. Her primary power deals with light waves, allowing her to render herself and others invisible. However, she can also project powerful fields of invisible psionic energy which she uses for a variety of offensive and defensive effects. Sue plays a central role in the lives of her brother, her husband, her children, and her close friend Ben Grimm.\nAn object of infatuation for Doctor Doom and, most notably, Namor the Sub-Mariner, Sues passive invisibility power translated into her frequent deployment as a damsel in distress during the teams early adventures. However, upon developing the ability to project powerful fields of energy, Sue Storm became a more powerful member of the Fantastic Four, and the teams second-in-command with a growing assertive confidence. While Sue operated somewhat in the shadow of her hot-headed brother, Johnny Storm, and her brilliant husband Reed Richards in the early years, she is now the soul of the Fantastic Four and one of the premiere heroes in the Marvel Universe."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "96",
        "_score" : 1.0,
        "_source" : {
          "name" : "Batwoman",
          "summary" : "Batwoman is a fictional character, a superheroine who appears in comic books published by DC Comics. In all incarnations, Batwoman is a wealthy heiress who—inspired by the notorious superhero Batman—chooses, like him, to put her wealth and resources towards funding a war on crime in her home of Gotham City. The identity of Batwoman is shared by two heroines in mainstream DC publications; both women are named Katherine Kane, with the original Batwoman commonly referred to by her nickname Kathy and the modern incarnation going by the name Kate.\nBatwoman was created by Bob Kane and Sheldon Moldoff with writer Edmond Hamilton under the direction of editor Jack Schiff, as part of an ongoing effort to expand Batmans cast of supporting characters. Batwoman began appearing in DC Comics stories beginning with Detective Comics #233, in which she was introduced as a love interest for Batman in order to combat the allegations of Batmans homosexuality arising from the controversial book Seduction of the Innocent. When Julius Schwartz became editor of the Batman-related comic books in 1964, he removed non-essential characters including Batwoman, Bat-Girl, Bat-Mite, and Bat-Hound. Later, the 1985 limited series Crisis on Infinite Earths retroactively established that Batwoman had never existed, though her alter ego Kathy Kane continued to be referred to occasionally."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "70",
        "_score" : 1.0,
        "_source" : {
          "name" : "Human Torch",
          "summary" : "The Human Torch is a fictional character, a superhero that appears in comic books published by Marvel Comics. He is a founding member of the Fantastic Four. A similar, unrelated character of the same name and powers had been created in 1939 by writer-artist Carl Burgos for Marvel Comics predecessor company, Timely Comics.\nLike the rest of the Fantastic Four, the Human Torch gained his powers on a spacecraft bombarded by cosmic rays. He can engulf his entire body in flames, is able to fly, can absorb fire harmlessly into his own body, and can control any nearby fire by sheer force of will. Flame on!, which the Torch customarily shouts when activating his full-body flame effect, has become his catchphrase.\nThe youngest of the group, he is brash and impetuous in comparison to his reticient and compassionate sister, Susan Storm, his sensible brother-in-law, Reed Richards, and the grumbling Ben Grimm.\nIn the early 1960s, he starred in a series of solo adventures, published in Strange Tales. He is also a friend and frequent ally of Spider-Man, who is approximately the same age as the Torch.\nChris Evans portrayed him in the 2005 film Fantastic Four, and its 2007 sequel Fantastic Four: Rise of the Silver Surfer."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "109",
        "_score" : 1.0,
        "_source" : {
          "name" : "Hawkman",
          "summary" : "Hawkman is a fictional character, a superhero who appears in comic books published by DC Comics. Created by writer Gardner Fox and artist Dennis Neville, the original Hawkman first appeared in Flash Comics #1, published by All-American Publications in 1940.\nSeveral incarnations of Hawkman have appeared in DC Comics, all of them characterized by the use of archaic weaponry and by large, artificial wings, attached to a harness made from the special Nth metal that allows flight. Most incarnations of Hawkman work closely with a partner/romantic interest named Hawkgirl or Hawkwoman.\nSince DC’s continuity was rewritten in the 1985 series Crisis on Infinite Earths, Hawkman’s history has become muddled with several new versions of the character appearing throughout the years, some associated with ancient Egypt and some with the fictional planet Thanagar. These versions of the character have starred in several series of various durations."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "51",
        "_score" : 1.0,
        "_source" : {
          "name" : "Iceman",
          "summary" : "Iceman is a fictional character, a superhero who appears in comic books published by Marvel Comics. He is a founding member of the X-Men. A mutant, Iceman has the ability of cryokinesis where he can freeze anything around him and can also turn his body into ice. Although he is an Omega-level mutant, Drake has yet to tap into his full mutant potential. He has, however, begun to take more interest over the years in developing his abilities. One of the original X-Men, Iceman has had a frequent presence in X-Men-related comics, video games, animated series, and movies.\nShawn Ashmore portrays Iceman in the X-Men films, and voices the character in The Super Hero Squad Show."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "43",
        "_score" : 1.0,
        "_source" : {
          "name" : "Martian Manhunter",
          "summary" : "The Martian Manhunter is a fictional character, a superhero that appears in comic books published by DC Comics. Created by writer Joseph Samachson and artist Joe Certa, the character first appeared in Detective Comics #225. The character is known for being one of the core members of the Justice League of America.\nJonn Jonzz has featured in other DC Comics-endorsed products, such as video games, television series, animated films, or merchandise like action figures and trading cards.\nSome plot events are described, below, using in-universe tone."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "Spider-Man",
          "summary" : "Spider-Man is a fictional character, a comic book superhero who appears in comic books published by Marvel Comics. Created by writer-editor Stan Lee and writer-artist Steve Ditko, he first appeared in Amazing Fantasy #15. Lee and Ditko conceived the character as an orphan being raised by his Aunt May and Uncle Ben, and as a teenager, having to deal with the normal struggles of adolescence in addition to those of a costumed crimefighter. Spider-Mans creators gave him super strength and agility, the ability to cling to most surfaces, shoot spider-webs using wrist-mounted devices of his own invention which he called web-shooters, and react to danger quickly with his spider-sense, enabling him to combat his foes.\nWhen Spider-Man first appeared in the early 1960s, teenagers in superhero comic books were usually relegated to the role of sidekick to the protagonist. The Spider-Man series broke ground by featuring Peter Parker, a teenage high school student and person behind Spider-Mans secret identity to whose self-obsessions with rejection, inadequacy, and loneliness young readers could relate. Unlike previous teen heroes such as Bucky and Robin, Spider-Man did not benefit from being the protégé of any adult superhero mentors like Captain America and Batman, and thus had to learn for himself that with great power there must also come great responsibility—a line included in a text box in the final panel of the first Spider-Man story, but later retroactively attributed to his guardian, the late Uncle Ben."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "Superman",
          "summary" : "Superman is an American fictional character, a comic book superhero who appears in comic books published by DC Comics. He is widely considered a national cultural icon. Superman was created by writer Jerry Siegel and artist Joe Shuster, high school students living in Cleveland, Ohio, in 1933; the character was sold to Detective Comics, Inc. in 1938. Superman first appeared in Action Comics #1 and subsequently appeared in various radio serials, television programs, films, newspaper strips, and video games. With the success of his adventures, Superman helped to create the superhero genre and establish its primacy within the American comic book.\nSupermans appearance is distinctive and iconic. He usually wears a blue costume, red cape, and stylized red-and-yellow S shield on his chest. This shield is used in a myriad of media to symbolize the character.\nThe origin story of Superman relates that he was born Kal-El on the planet Krypton, before being rocketed to Earth as an infant by his scientist father Jor-El, moments before Kryptons destruction. Discovered and adopted by a Kansas farmer and his wife, the child is raised as Clark Kent and imbued with a strong moral compass. Very early he started to display superhuman abilities, which upon reaching maturity, he resolved to use for the benefit of humanity. Superman resides and operates in the fictional American city of Metropolis. As Clark Kent, he is a journalist for a Metropolis newspaper called the Daily Planet."
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "69",
        "_score" : 1.0,
        "_source" : {
          "name" : "Human Torch",
          "summary" : "The Human Torch is a fictional character, a superhero that appears in comic books published by Marvel Comics. He is a founding member of the Fantastic Four. A similar, unrelated character of the same name and powers had been created in 1939 by writer-artist Carl Burgos for Marvel Comics predecessor company, Timely Comics.\nLike the rest of the Fantastic Four, the Human Torch gained his powers on a spacecraft bombarded by cosmic rays. He can engulf his entire body in flames, is able to fly, can absorb fire harmlessly into his own body, and can control any nearby fire by sheer force of will. Flame on!, which the Torch customarily shouts when activating his full-body flame effect, has become his catchphrase.\nThe youngest of the group, he is brash and impetuous in comparison to his reticient and compassionate sister, Susan Storm, his sensible brother-in-law, Reed Richards, and the grumbling Ben Grimm.\nIn the early 1960s, he starred in a series of solo adventures, published in Strange Tales. He is also a friend and frequent ally of Spider-Man, who is approximately the same age as the Torch.\nChris Evans portrayed him in the 2005 film Fantastic Four, and its 2007 sequel Fantastic Four: Rise of the Silver Surfer."
        }
      }
    ]
  }
}

3. Melakukan highlighting pada hasil pencarian

Hasil pencarian akan lebih enak bila disertakan bagian mana yang mengandung kata yang cocok. Elasticsearch memiliki fitur highlighting untuk menunjukkan bagian dokumen yang cocok dengan pencarian. Mari kita coba query berikut ini, dimana bila ada kata "fictional" dan "comic" maka akan diapit oleh tag "span".
{
    "from":0,
    "size":10,
    "sort":[
        "_score"
    ],
    "query":{
        "bool":{
            "must":{
                "wildcard":{
                    "name":"*man*"
                }
            },
        "filter":[
            {"match":{"summary":"fictional"}},
            {"match":{"summary":"comic"}}
        ]
    }
},
"highlight" : {
    "pre_tags": ["<span>"],
    "post_tags": ["</span>"],
    "fields":{
        "summary":{}
    }
}

}

Sekarang mari kita eksekusi:

$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 131,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 9,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "103",
        "_score" : 1.0,
        "_source" : {
          "name" : "Invisible Woman",
          "summary" : "Susan Sue Storm Richards is a fictional character, a superheroine that appears in comic books published by Marvel Comics. She was the first female superhero created by Marvel in the Silver Age of Comics. Like the other founding members of the Fantastic Four, Sue received her powers after being exposed to a cosmic storm. Her primary power deals with light waves, allowing her to render herself and others invisible. However, she can also project powerful fields of invisible psionic energy which she uses for a variety of offensive and defensive effects. Sue plays a central role in the lives of her brother, her husband, her children, and her close friend Ben Grimm.\nAn object of infatuation for Doctor Doom and, most notably, Namor the Sub-Mariner, Sues passive invisibility power translated into her frequent deployment as a damsel in distress during the teams early adventures. However, upon developing the ability to project powerful fields of energy, Sue Storm became a more powerful member of the Fantastic Four, and the teams second-in-command with a growing assertive confidence. While Sue operated somewhat in the shadow of her hot-headed brother, Johnny Storm, and her brilliant husband Reed Richards in the early years, she is now the soul of the Fantastic Four and one of the premiere heroes in the Marvel Universe."
        },
        "highlight" : {
          "summary" : [
            "Susan Sue Storm Richards is a <span>fictional</span> character, a superheroine that appears in <span>comic</span> books"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "96",
        "_score" : 1.0,
        "_source" : {
          "name" : "Batwoman",
          "summary" : "Batwoman is a fictional character, a superheroine who appears in comic books published by DC Comics. In all incarnations, Batwoman is a wealthy heiress who—inspired by the notorious superhero Batman—chooses, like him, to put her wealth and resources towards funding a war on crime in her home of Gotham City. The identity of Batwoman is shared by two heroines in mainstream DC publications; both women are named Katherine Kane, with the original Batwoman commonly referred to by her nickname Kathy and the modern incarnation going by the name Kate.\nBatwoman was created by Bob Kane and Sheldon Moldoff with writer Edmond Hamilton under the direction of editor Jack Schiff, as part of an ongoing effort to expand Batmans cast of supporting characters. Batwoman began appearing in DC Comics stories beginning with Detective Comics #233, in which she was introduced as a love interest for Batman in order to combat the allegations of Batmans homosexuality arising from the controversial book Seduction of the Innocent. When Julius Schwartz became editor of the Batman-related comic books in 1964, he removed non-essential characters including Batwoman, Bat-Girl, Bat-Mite, and Bat-Hound. Later, the 1985 limited series Crisis on Infinite Earths retroactively established that Batwoman had never existed, though her alter ego Kathy Kane continued to be referred to occasionally."
        },
        "highlight" : {
          "summary" : [
            "Batwoman is a <span>fictional</span> character, a superheroine who appears in <span>comic</span> books published by DC Comics",
            " of the Innocent. When Julius Schwartz became editor of the Batman-related <span>comic</span> books in 1964, he"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "70",
        "_score" : 1.0,
        "_source" : {
          "name" : "Human Torch",
          "summary" : "The Human Torch is a fictional character, a superhero that appears in comic books published by Marvel Comics. He is a founding member of the Fantastic Four. A similar, unrelated character of the same name and powers had been created in 1939 by writer-artist Carl Burgos for Marvel Comics predecessor company, Timely Comics.\nLike the rest of the Fantastic Four, the Human Torch gained his powers on a spacecraft bombarded by cosmic rays. He can engulf his entire body in flames, is able to fly, can absorb fire harmlessly into his own body, and can control any nearby fire by sheer force of will. Flame on!, which the Torch customarily shouts when activating his full-body flame effect, has become his catchphrase.\nThe youngest of the group, he is brash and impetuous in comparison to his reticient and compassionate sister, Susan Storm, his sensible brother-in-law, Reed Richards, and the grumbling Ben Grimm.\nIn the early 1960s, he starred in a series of solo adventures, published in Strange Tales. He is also a friend and frequent ally of Spider-Man, who is approximately the same age as the Torch.\nChris Evans portrayed him in the 2005 film Fantastic Four, and its 2007 sequel Fantastic Four: Rise of the Silver Surfer."
        },
        "highlight" : {
          "summary" : [
            "The Human Torch is a <span>fictional</span> character, a superhero that appears in <span>comic</span> books published by"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "109",
        "_score" : 1.0,
        "_source" : {
          "name" : "Hawkman",
          "summary" : "Hawkman is a fictional character, a superhero who appears in comic books published by DC Comics. Created by writer Gardner Fox and artist Dennis Neville, the original Hawkman first appeared in Flash Comics #1, published by All-American Publications in 1940.\nSeveral incarnations of Hawkman have appeared in DC Comics, all of them characterized by the use of archaic weaponry and by large, artificial wings, attached to a harness made from the special Nth metal that allows flight. Most incarnations of Hawkman work closely with a partner/romantic interest named Hawkgirl or Hawkwoman.\nSince DC’s continuity was rewritten in the 1985 series Crisis on Infinite Earths, Hawkman’s history has become muddled with several new versions of the character appearing throughout the years, some associated with ancient Egypt and some with the fictional planet Thanagar. These versions of the character have starred in several series of various durations."
        },
        "highlight" : {
          "summary" : [
            "Hawkman is a <span>fictional</span> character, a superhero who appears in <span>comic</span> books published by DC Comics",
            " ancient Egypt and some with the <span>fictional</span> planet Thanagar. These versions of the character have starred in several series of various durations."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "51",
        "_score" : 1.0,
        "_source" : {
          "name" : "Iceman",
          "summary" : "Iceman is a fictional character, a superhero who appears in comic books published by Marvel Comics. He is a founding member of the X-Men. A mutant, Iceman has the ability of cryokinesis where he can freeze anything around him and can also turn his body into ice. Although he is an Omega-level mutant, Drake has yet to tap into his full mutant potential. He has, however, begun to take more interest over the years in developing his abilities. One of the original X-Men, Iceman has had a frequent presence in X-Men-related comics, video games, animated series, and movies.\nShawn Ashmore portrays Iceman in the X-Men films, and voices the character in The Super Hero Squad Show."
        },
        "highlight" : {
          "summary" : [
            "Iceman is a <span>fictional</span> character, a superhero who appears in <span>comic</span> books published by Marvel Comics"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "43",
        "_score" : 1.0,
        "_source" : {
          "name" : "Martian Manhunter",
          "summary" : "The Martian Manhunter is a fictional character, a superhero that appears in comic books published by DC Comics. Created by writer Joseph Samachson and artist Joe Certa, the character first appeared in Detective Comics #225. The character is known for being one of the core members of the Justice League of America.\nJonn Jonzz has featured in other DC Comics-endorsed products, such as video games, television series, animated films, or merchandise like action figures and trading cards.\nSome plot events are described, below, using in-universe tone."
        },
        "highlight" : {
          "summary" : [
            "The Martian Manhunter is a <span>fictional</span> character, a superhero that appears in <span>comic</span> books published"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "Spider-Man",
          "summary" : "Spider-Man is a fictional character, a comic book superhero who appears in comic books published by Marvel Comics. Created by writer-editor Stan Lee and writer-artist Steve Ditko, he first appeared in Amazing Fantasy #15. Lee and Ditko conceived the character as an orphan being raised by his Aunt May and Uncle Ben, and as a teenager, having to deal with the normal struggles of adolescence in addition to those of a costumed crimefighter. Spider-Mans creators gave him super strength and agility, the ability to cling to most surfaces, shoot spider-webs using wrist-mounted devices of his own invention which he called web-shooters, and react to danger quickly with his spider-sense, enabling him to combat his foes.\nWhen Spider-Man first appeared in the early 1960s, teenagers in superhero comic books were usually relegated to the role of sidekick to the protagonist. The Spider-Man series broke ground by featuring Peter Parker, a teenage high school student and person behind Spider-Mans secret identity to whose self-obsessions with rejection, inadequacy, and loneliness young readers could relate. Unlike previous teen heroes such as Bucky and Robin, Spider-Man did not benefit from being the protégé of any adult superhero mentors like Captain America and Batman, and thus had to learn for himself that with great power there must also come great responsibility—a line included in a text box in the final panel of the first Spider-Man story, but later retroactively attributed to his guardian, the late Uncle Ben."
        },
        "highlight" : {
          "summary" : [
            "Spider-Man is a <span>fictional</span> character, a <span>comic</span> book superhero who appears in <span>comic</span> books published by",
            " to combat his foes.\nWhen Spider-Man first appeared in the early 1960s, teenagers in superhero <span>comic</span>"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "Superman",
          "summary" : "Superman is an American fictional character, a comic book superhero who appears in comic books published by DC Comics. He is widely considered a national cultural icon. Superman was created by writer Jerry Siegel and artist Joe Shuster, high school students living in Cleveland, Ohio, in 1933; the character was sold to Detective Comics, Inc. in 1938. Superman first appeared in Action Comics #1 and subsequently appeared in various radio serials, television programs, films, newspaper strips, and video games. With the success of his adventures, Superman helped to create the superhero genre and establish its primacy within the American comic book.\nSupermans appearance is distinctive and iconic. He usually wears a blue costume, red cape, and stylized red-and-yellow S shield on his chest. This shield is used in a myriad of media to symbolize the character.\nThe origin story of Superman relates that he was born Kal-El on the planet Krypton, before being rocketed to Earth as an infant by his scientist father Jor-El, moments before Kryptons destruction. Discovered and adopted by a Kansas farmer and his wife, the child is raised as Clark Kent and imbued with a strong moral compass. Very early he started to display superhuman abilities, which upon reaching maturity, he resolved to use for the benefit of humanity. Superman resides and operates in the fictional American city of Metropolis. As Clark Kent, he is a journalist for a Metropolis newspaper called the Daily Planet."
        },
        "highlight" : {
          "summary" : [
            "Superman is an American <span>fictional</span> character, a <span>comic</span> book superhero who appears in <span>comic</span> books",
            " establish its primacy within the American <span>comic</span> book.\nSupermans appearance is distinctive and iconic",
            " the benefit of humanity. Superman resides and operates in the <span>fictional</span> American city of Metropolis"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "69",
        "_score" : 1.0,
        "_source" : {
          "name" : "Human Torch",
          "summary" : "The Human Torch is a fictional character, a superhero that appears in comic books published by Marvel Comics. He is a founding member of the Fantastic Four. A similar, unrelated character of the same name and powers had been created in 1939 by writer-artist Carl Burgos for Marvel Comics predecessor company, Timely Comics.\nLike the rest of the Fantastic Four, the Human Torch gained his powers on a spacecraft bombarded by cosmic rays. He can engulf his entire body in flames, is able to fly, can absorb fire harmlessly into his own body, and can control any nearby fire by sheer force of will. Flame on!, which the Torch customarily shouts when activating his full-body flame effect, has become his catchphrase.\nThe youngest of the group, he is brash and impetuous in comparison to his reticient and compassionate sister, Susan Storm, his sensible brother-in-law, Reed Richards, and the grumbling Ben Grimm.\nIn the early 1960s, he starred in a series of solo adventures, published in Strange Tales. He is also a friend and frequent ally of Spider-Man, who is approximately the same age as the Torch.\nChris Evans portrayed him in the 2005 film Fantastic Four, and its 2007 sequel Fantastic Four: Rise of the Silver Surfer."
        },
        "highlight" : {
          "summary" : [
            "The Human Torch is a <span>fictional</span> character, a superhero that appears in <span>comic</span> books published by"
          ]
        }
      }
    ]
  }
}

4. Melakukan bool query yang lebih kompleks

Sekarang kita akan coba menggunakan query menggunakan "should" yang dapat dianggap sebagai query "OR" di SQL. Kita akan coba melakukan semacam query "SELECT * FROM superhero WHERE summary LIKE '%villain%' OR summary LIKE '%superhero%'" walaupun sebenarnya tidak dapat dianggap mirip.
{
    "from":0,
    "size":10,
    "sort":[
        "_score"
    ],
    "query":{
        "bool":{
            "should":[
                {
                    "match":{
                        "summary":"villain"
                    }
                },
                {
                    "match":{
                        "summary":"superhero"
                    }
                }
            ]
        }
    },
    "highlight" : {
        "pre_tags": ["<span>"],
        "post_tags": ["</span>"],
        "fields":{
            "summary":{}
        }
    }
}
Sekarang mari kita jalankan query diatas:
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 34,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 79,
    "max_score" : 2.6498606,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "29",
        "_score" : 2.6498606,
        "_source" : {
          "name" : "Deathstroke",
          "summary" : "Deathstroke the Terminator is a fictional comic book supervillain, and sometimes antihero, who appears in books published by DC Comics. Created by writer Marv Wolfman and artist George Pérez, he is a mercenary and assassin who first appeared in The New Teen Titans #2. Wizard Magazine rated him the 84th greatest villain of all time and the 72nd greatest comic book character of all time. Also, in 2009, Deathstroke was ranked as IGNs 32nd greatest comic book villain of all time."
        },
        "highlight" : {
          "summary" : [
            " 84th greatest <span>villain</span> of all time and the 72nd greatest comic book character of all time. Also, in",
            " 2009, Deathstroke was ranked as IGNs 32nd greatest comic book <span>villain</span> of all time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "106",
        "_score" : 2.6231508,
        "_source" : {
          "name" : "Black Adam",
          "summary" : "Black Adam is a fictional character created in 1945 by Otto Binder & C. C. Beck. Originally created as a villain for Fawcett Comics Marvel Family, Black Adam was revived as a recurring supervillain after DC Comics began publishing Captain Marvel/Marvel Family stories under the title Shazam! in the 1970s. As originally depicted, Black Adam was a corrupted ancient Egyptian predecessor of Captain Marvel who fought his way to modern times to challenge the hero and his Marvel Family associates. Since the turn of the 21st century, Adam has been redefined by DC writers Jerry Ordway, Geoff Johns, and David S. Goyer as a corrupted antihero attempting to clear his name. Featured roles in comic books series such as JSA, Villains United, Infinite Crisis, and 52 have elevated the character to a level of prominence in DC Comics. In 2009, Black Adam was ranked as IGNs 16th Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " as a <span>villain</span> for Fawcett Comics Marvel Family, Black Adam was revived as a recurring supervillain",
            " of prominence in DC Comics. In 2009, Black Adam was ranked as IGNs 16th Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "39",
        "_score" : 2.5381417,
        "_source" : {
          "name" : "Quicksilver",
          "summary" : "Quicksilver is a fictional character that appears in comic books published by Marvel Comics. The character first appears in X-Men #4 and was created by Stan Lee and Jack Kirby. He is the son of Magneto, the twin brother of the Scarlet Witch, and the paternal half-brother of Polaris.\nDebuting in the Silver Age of comic books, Quicksilver has featured in four decades of Marvel continuity, starring in the self-titled series Quicksilver and as a regular team member in superhero title the Avengers. The character has also appeared in other Marvel-endorsed products such as animated films; arcade and video games; television series and merchandise such as action figures and trading cards.\nIn 2006, IGN named Quicksilver #23 on their list of The Top 25 X-Men Of All Time commenting that Quicksilver was the shining example of a villain turned good."
        },
        "highlight" : {
          "summary" : [
            " in the self-titled series Quicksilver and as a regular team member in <span>superhero</span> title the Avengers",
            ", IGN named Quicksilver #23 on their list of The Top 25 X-Men Of All Time commenting that Quicksilver was the shining example of a <span>villain</span> turned good."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "20",
        "_score" : 2.4191983,
        "_source" : {
          "name" : "Captain Marvel",
          "summary" : "Captain Marvel, also known as Shazam, is a fictional comic book superhero, originally published by Fawcett Comics and later by DC Comics. Created in 1939 by artist C. C. Beck and writer Bill Parker, the character first appeared in Whiz Comics #2. With a premise that taps adolescent fantasy, Captain Marvel is the alter ego of Billy Batson, a youth who works as a radio news reporter and was chosen to be a champion of good by the wizard Shazam. Whenever Billy speaks the wizards name, he is struck by a magic lightning bolt that transforms him into an adult superhero empowered with the abilities of six archetypal, historical figures. Several friends and family members, most notably Marvel Family cohorts Mary Marvel and Captain Marvel Jr., can share Billys power and become Marvels themselves.\nHailed as The Worlds Mightiest Mortal in his adventures, Captain Marvel was nicknamed The Big Red Cheese by arch-villain Doctor Sivana, an epithet later adopted by Captain Marvels fans. Based on sales, Captain Marvel was the most popular superhero of the 1940s, as his Captain Marvel Adventures comic book series sold more copies than Superman and the other competing books of the time. Captain Marvel was also the first comic book superhero to be adapted to film, in a 1941 Republic Pictures serial titled Adventures of Captain Marvel."
        },
        "highlight" : {
          "summary" : [
            "Captain Marvel, also known as Shazam, is a fictional comic book <span>superhero</span>, originally published by",
            " by a magic lightning bolt that transforms him into an adult <span>superhero</span> empowered with the abilities",
            " Cheese by arch-<span>villain</span> Doctor Sivana, an epithet later adopted by Captain Marvels fans. Based on sales",
            ", Captain Marvel was the most popular <span>superhero</span> of the 1940s, as his Captain Marvel Adventures comic",
            " was also the first comic book <span>superhero</span> to be adapted to film, in a 1941 Republic Pictures serial titled Adventures of Captain Marvel."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "16",
        "_score" : 2.3085327,
        "_source" : {
          "name" : "Magneto",
          "summary" : "Magneto is a fictional character that appears in comic books published by Marvel Comics. He has most often been the primary villain of the X-Men comics, as well as the TV shows and the films; although in the comics, he has been an ally and even member of the X-Men at times. The character first appears in X-Men #1, and was created by writer Stan Lee and artist Jack Kirby. A powerful mutant with the ability to generate and control magnetic fields, Magneto desired mutants to eventually dominate the human race as he viewed humans as an outdated species that no longer deserves its continual domination over the world. However, writers have since fleshed out his character and origin, revealing him to be a Jewish Holocaust survivor whose actions are driven by the purpose of protecting the mutant race from suffering a similar fate. His role in comics has varied from supervillain to antihero to superhero. His characters early history has been compared with the civil rights leader Malcolm X and Jewish ultranationalist Meir Kahane.\nSir Ian McKellen portrayed Magneto through the X-Men film series. Michael Fassbender plays a younger version of the character in the 2011 prequel X-Men: First Class, and the upcoming 2014 sequel X-Men: Days of Future Past. Magneto was ranked number 1 by IGNs Top 100 Comic Book Villains list, was listed number 17 in Wizards Top 100 Greatest Villains Ever list, and was ranked as the 9th Greatest Comic Book Character Ever in Wizards list of the 200 Greatest Comic Book Characters of All Time, the second highest villain on that list."
        },
        "highlight" : {
          "summary" : [
            " most often been the primary <span>villain</span> of the X-Men comics, as well as the TV shows and the films",
            " <span>superhero</span>. His characters early history has been compared with the civil rights leader Malcolm X and",
            " Comic Book Characters of All Time, the second highest <span>villain</span> on that list."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "91",
        "_score" : 2.2504275,
        "_source" : {
          "name" : "Superboy-Prime",
          "summary" : "Superboy-Prime, also known as Superman-Prime, or simply Prime, is a DC Comics superhero turned supervillain, and one of several alternate Supermen. The character first appeared in DC Comics Presents #87, and was created by Elliot S! Maggin and Curt Swan.\nSuperboy-Prime is from a parallel Earth called Earth-Prime that had no super-heroes. There, Superman and the other comic superheroes were fictional characters only seen in comic books. The Earth-Prime universe was erased during the Crisis on Infinite Earths, and Superboy Prime ended up in a paradise dimension where during that time, he found himself unable to let go of his former life and his destiny as Earths greatest hero.\nOver time, his convictions and morals became warped and as such, Prime still harbors a strong belief that becoming Superman is his calling despite the fact that he has become a psychotic and very dangerous villain who is one of the most dangerous villains that Superman and the rest of the superheroes have ever encountered due to Primes sheer ruthlessness and thirst for destruction as he seeks to pursue his destiny."
        },
        "highlight" : {
          "summary" : [
            "Superboy-Prime, also known as Superman-Prime, or simply Prime, is a DC Comics <span>superhero</span> turned",
            " Superman is his calling despite the fact that he has become a psychotic and very dangerous <span>villain</span>"
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "44",
        "_score" : 2.1955879,
        "_source" : {
          "name" : "Riddler",
          "summary" : "The Riddler is a fictional character, a comic book supervillain appearing in comic books published by DC Comics. He usually appears as an enemy of Batman. Created by writer Bill Finger and artist Dick Sprang, the character first appeared in Detective Comics #140. In 2009, the Riddler was ranked as IGNs 59th Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " Dick Sprang, the character first appeared in Detective Comics #140. In 2009, the Riddler was ranked as IGNs 59th Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "142",
        "_score" : 2.133566,
        "_source" : {
          "name" : "Sebastian Shaw",
          "summary" : "Sebastian Hiram Shaw is a fictional character, a supervillain who appears in comic books published by Marvel Comics. He was frequently an adversary of the X-Men.\nA mutant, Shaw possesses the ability to absorb energy and transform it into raw strength. He is the leader of the New York branch of the Hellfire Club, an exclusive secret society bent on world domination, although to the public, he is a legitimate businessman and ordinary human. He once funded the mutant-hunting Sentinel program to keep it under his thumb. In 2009, Shaw was named IGNs 55th Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " keep it under his thumb. In 2009, Shaw was named IGNs 55th Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "81",
        "_score" : 2.0714936,
        "_source" : {
          "name" : "Red Skull",
          "summary" : "The Red Skull is a fictional character who appears in comic books published by Marvel Comics. He is the archenemy of the superhero Captain America, and is portrayed as a Nazi agent. Created by Joe Simon, Jack Kirby and France Herron, the concept of the Red Skull first appeared in Captain America Comics #1 in March 1941, with the character of Johann Schmidt first appearing in Captain America Comics #7 in October 1941. He has appeared as a recurring enemy of Captain America in various ongoing series, limited series and alternate reality series in the years since.\nThe character has been adapted to a variety of other media platforms, including animated television series, video games, and live-action feature films. He was portrayed by actor Hugo Weaving in the 2011 film Captain America: The First Avenger.\nThe Red Skull was ranked number 21 on Wizard Magazines Top 100 Greatest Villains Ever list and was also ranked as IGNs 14th Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " the archenemy of the <span>superhero</span> Captain America, and is portrayed as a Nazi agent. Created by Joe",
            " list and was also ranked as IGNs 14th Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "60",
        "_score" : 2.0441234,
        "_source" : {
          "name" : "Carnage",
          "summary" : "Carnage is a fictional comic book supervillain appearing in books published by Marvel Comics, usually as an enemy of Spider-Man. The character first appeared as Cletus Kasady in The Amazing Spider-Man #344 and as Carnage in The Amazing Spider-Man #360, and was created by writer David Michelinie and artist Mark Bagley, based on elements of the precursor character Venom. In 2009, Carnage was ranked as IGNs 90th Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " as IGNs 90th Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      }
    ]
  }
}

Agar semakin seru, kita akan mencoba semacam query "SELECT * FROM superhero WHERE (summary LIKE '%villain%' AND summary LIKE '%military%') OR (summary LIKE '%superhero%' AND summary LIKE '%mythology%')". Sehingga pencarian kita semakin kaya dan detail:

{
    "from":0,
    "size":10,
    "sort":[
        "_score"
    ],
    "query":{
        "bool":{
            "should":[
                {
                    "bool":{
                        "must": {
                            "match":{
                                "summary":"villain"
                            }
                        },
                        "filter": {
                            "match":{
                                "summary":"military"
                            }
                        }
                    }
                },
                {
                    "bool":{
                        "must": {
                            "match":{
                                "summary":"superhero"
                            }
                        },
                        "filter": {
                            "match":{
                                "summary":"mythology"
                            }
                        }
                    }
                }
            ]
        }
    },
    "highlight" : {
        "pre_tags": ["<span>"],
        "post_tags": ["</span>"],
        "fields":{
            "summary":{}
        }
    }
}

Bila dijalankan maka akan muncul output berikut:

$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query-9.json'
{
  "took" : 14,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 1.8998765,
    "hits" : [
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "57",
        "_score" : 1.8998765,
        "_source" : {
          "name" : "Thunderbolt Ross",
          "summary" : "General Thaddeus E. Thunderbolt Ross is a fictional character who appears in comic books published by Marvel Comics. Ross is a United States military officer, the father of Betty Ross, ex-father in-law of Glenn Talbot, father in-law of Dr. Bruce Banner, and was head of the Gamma Bomb Project that turned Banner into the Hulk. After the creation of the Hulk, Ross pursues the creature with a growing obsession, and after learning that Banner and the Hulk are one and the same, Ross hunts Banner as well. In 2008, Ross appeared as the Red Hulk, into which he had been transformed in order to better combat his nemesis.\nIn 2009, Thunderbolt Ross was named IGNs 71st Greatest Comic Book Villain of All Time."
        },
        "highlight" : {
          "summary" : [
            " by Marvel Comics. Ross is a United States <span>military</span> officer, the father of Betty Ross, ex-father in",
            " combat his nemesis.\nIn 2009, Thunderbolt Ross was named IGNs 71st Greatest Comic Book <span>Villain</span> of All Time."
          ]
        }
      },
      {
        "_index" : "demo",
        "_type" : "superhero",
        "_id" : "9",
        "_score" : 1.1285394,
        "_source" : {
          "name" : "Thor",
          "summary" : "Thor is a fictional character, a superhero who appears in comic books published by Marvel Comics. The character first appeared in Journey into Mystery #83 and was created by editor-plotter Stan Lee, scripter Larry Lieber, and penciller Jack Kirby. The mythological Thor had appeared previously in Venus #12-13.\nDebuting in the Silver Age of Comic Books, the character is based on the god Thor of Norse mythology. He has starred in several ongoing series and limited series, and has been a perennial member of the superhero team the Avengers, appearing in each of the four volumes. The character has also appeared in associated Marvel merchandise including animated television series, clothing, toys, trading cards, video games, and movies.\nThe 2011 film Thor, based on the character and comic, was directed by Kenneth Branagh and starred Chris Hemsworth as Thor. Hemsworth reappears as Thor in The Avengers, and Thor: The Dark World is set for release in 2013. Thor placed 14th on IGNs Top 100 Comic Book Heroes of All Time in 2011."
        },
        "highlight" : {
          "summary" : [
            "Thor is a fictional character, a <span>superhero</span> who appears in comic books published by Marvel Comics",
            " Norse <span>mythology</span>. He has starred in several ongoing series and limited series, and has been a perennial",
            " member of the <span>superhero</span> team the Avengers, appearing in each of the four volumes. The character has"
          ]
        }
      }
    ]
  }
}

5. Mencari dokumen melalui URI

Selain melalui request body search, kamu juga dapat melakukannya melalui URI dimana melewatkan beberapa parameter yang lebih sederhana:
curl -XGET 'http://localhost:9200/demo/superhero/_search?pretty=true&q=name:Spider-Man'
curl -XGET 'http://localhost:9200/demo/superhero/_search?pretty=true&q=name:*man&size=5'
curl -XGET 'http://localhost:9200/demo/superhero/_count?pretty=true&q=name:*man'

6. Mencari saran dari hasil pencarian

Terakhir, karena kita akan melihat bagaimana suatu suggestion bekerja di Elasticsearch, maka kamu harus menggunakan "suggest" di dalam request body search. Dimana bila kita mengetik sebuah kata yang salah, akan diberikan rekomendasi kata yang memiliki kemiripan dengan kata - kata yang ada di dalam indeks:
{
    "size":0,
    "sort":[
        "_score"
    ],
    "query":{
        "match_all":{}
    },
    "suggest" : {
        "my-suggest":{
            "text":"hera",
            "term":{
                "field":"summary"
            }
        }
    }
}
Bila query diatas kita jalankan, maka akan muncul output berikut:
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query.json'
{
  "took" : 30,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 149,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "suggest" : {
    "my-suggest" : [
      {
        "text" : "hera",
        "offset" : 0,
        "length" : 4,
        "options" : [
          {
            "text" : "hero",
            "score" : 0.75,
            "freq" : 15
          },
          {
            "text" : "herb",
            "score" : 0.75,
            "freq" : 3
          },
          {
            "text" : "her",
            "score" : 0.6666666,
            "freq" : 22
          },
          {
            "text" : "head",
            "score" : 0.5,
            "freq" : 6
          },
          {
            "text" : "henry",
            "score" : 0.5,
            "freq" : 2
          }
        ]
      }
    ]
  }
}
Kita coba kata yang lain:
$ curl -XGET http://localhost:9200/demo/superhero/_search?pretty=true -d '@query-7.json'
{
  "took" : 16,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 149,
    "max_score" : 0.0,
    "hits" : [ ]
  },
  "suggest" : {
    "my-suggest" : [
      {
        "text" : "supper",
        "offset" : 0,
        "length" : 6,
        "options" : [
          {
            "text" : "super",
            "score" : 0.8,
            "freq" : 14
          },
          {
            "text" : "surfer",
            "score" : 0.6666666,
            "freq" : 7
          },
          {
            "text" : "support",
            "score" : 0.6666666,
            "freq" : 2
          }
        ]
      }
    ]
  }
}
Di urutan teratas, score terbesar akan dimunculkan terlebih dahulu begitupun dengan jumlah kemunculan terbanyak. Semakin kebawah akan semakin tidak mirip. Inilah salah satu kelebihan yang dimiliki oleh Elasticsearch sehingga sangat cocok bila digunakan didalam aplikasi web yang sedang kamu kembangkan.

7. Referensi

  • Elasticsearch Official Documentation
  • Tutorialspoint - Elasticsearch
(arslan/elasticsearch)