簡體   English   中英

將其輸出為JSON格式以供Elasticsearch使用嗎?

[英]Output this into JSON Format for use in elasticsearch?

我有一個python代碼,可找到基本文件中存在的單詞及其頻率。 這是代碼

import os
import re
import sys

d=[]

with open("all_words_to_find.txt") as f:
    d = map(str.rstrip, f.readlines())

file_name = sys.argv[1]
fp =open(file_name,"r")

word_count ={}

found = []
for line in fp:
    for word in d:
        if word in line:
            found.append(word)

#print(found)
fo = []

for val in found:
    va = val.rstrip()
    fo.append(va)

#print fo

with open('output.txt','w') as fp:
    for value in [ele for ind, ele in enumerate(fo,1) if ele not in fo[ind:]]:
        fp.write("{} : {} \n".format(value,fo.count(value)))

輸出為:

word1 : 3
word2 : 4

我希望輸出為:

que = {
     "query": {
         "bool": {
            "must": [
                { "match": {
                    "section": {
                        "query": "word1",
                        "boost": 3
                    },
                    "section": {
                        "query" : "word2",
                        "boost" : 4
                    }
                }}
            ]
        }
    }
}

我該如何實現,謝謝您的幫助!

盡管我不太確定要通過查詢實現什么,並且此處提到的查詢不正確。 但我的假設是您想要這樣的東西

{
    "query": {
        "bool": {
            "must": [{
                "match": {
                    "section": {
                        "query": "word1",
                        "boost": "3"
                    }
                }
            }, {
                "match": {
                    "section": {
                        "query": "word2",
                        "boost": "4"
                    }
                }
            }]
        }
    }
}

import json

def convert_to_es_query(file):
    basequery = {}
    bool_query = {}
    must_query = []
    bool_query["bool"] = {"must": must_query}
    basequery["query"] = bool_query
    with open(file) as f:
        for line in f:
            word, boost = line.split(':')
            must_query.append({"match": {"section": {"query": word.strip(), 
"boost": boost.strip()}}})

    return json.dumps(basequery)

盡管我建議實現此類目標的最佳方法是使用搜索模板...。它們真棒。 但是由於我對您的elasticsearch查詢不太確定,因此無法制定一個模板。 但是您可以看一看https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM